﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Data;
using System.Configuration;

using CE.Database;
using CE.CarInsurance;
using CE.Configuration;
using CE.Mail;
using CE.Global;
using System.Net;
using System.Text;
using CE.User;
using CE.Security;

public partial class car_insurance_promo_results : System.Web.UI.Page
{
    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        #region Promotion Status
        bool _IsPromo = false;
        string _Promo = CE.Global.General.GetUTCDateTime().ToString("yyyyMMdd");
        Int64 _intPromo = 0;
        if (!Int64.TryParse(_Promo, out _intPromo))
        {
            _intPromo = 0;
        }
        //if (Session["Language"] != null & Session["Language"].ToString() == "en-US")
        //{
        if ((_intPromo >= 20150413 && _intPromo <= 20150430) || (_intPromo >= 25580413 && _intPromo <= 25580430))
        {
            _IsPromo = true;
        }
        //}
        //else if (Session["Language"] != null & Session["Language"].ToString() == "th-TH")
        //{
        //    if (_intPromo >= 25580413 && _intPromo <= 25580430)
        //    {
        //        _IsPromo = true;
        //    }
        //}
        if (!_IsPromo)
        {
            Response.Redirect("car-quote.aspx");
        }
        #endregion

        if (Session[General.CarId] != null && Session[General.CarId].ToString() != "")
        {
            if (!Page.IsPostBack)
            {
                Int64 _userId = 0;
                if (Request.QueryString["qid"] != null && Request.QueryString["qid"].ToString() != string.Empty)
                {
                    hdnQuoteId.Value = Request.QueryString["qid"].ToString();
                }
                if (Request.QueryString["cid"] != null && Request.QueryString["cid"].ToString() != string.Empty)
                {
                    hdnCarId.Value = Request.QueryString["cid"].ToString();
                }
                if (Request.QueryString["pid"] != null && Request.QueryString["pid"].ToString() != string.Empty)
                {
                    hdnPolicyId.Value = Request.QueryString["pid"].ToString();
                }

                #region Call Me - No match found
                divCallMe.Visible = true;
                divCallMeMessage.Visible = false;
                if (Request.QueryString["sent"] != null && Request.QueryString["sent"].ToString() != string.Empty && Request.QueryString["sent"].ToString() == "1")
                {
                    divCallMeMessage.Visible = true;
                    divCallMe.Visible = false;
                }
                LoadTitles();
                txtName.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtName.ClientID + "','" + rfvName.ClientID + "','" + revName.ClientID + "');DefaultName(this, event);");
                txtName.Attributes.Add("onfocus", "ClearText(this, event);");
                txtEmail.Attributes.Add("onblur", "RemoveSpace(this);ShowValidationEffectTwo('" + txtEmail.ClientID + "','" + rfvEmail.ClientID + "','" + revEmail.ClientID + "');DefaultEmail(this, event);");
                txtEmail.Attributes.Add("onfocus", "ClearText(this, event);");
                txtMobile.Attributes.Add("onblur", "RemoveSpace(this);ShowValidationEffectTwo('" + txtMobile.ClientID + "','" + rfvMobile.ClientID + "','" + revMobile.ClientID + "');DefaultPhone(this, event);");
                txtMobile.Attributes.Add("onfocus", "ClearText(this, event);");
                #endregion

                HttpCookie _cookie = Request.Cookies.Get("GGMobileQuote");
                if (_cookie != null)
                {
                    string _strEmail = "";
                    string _strName = "";
                    string _strMobile = "";
                    if (_cookie != null)
                    {
                        _strEmail = MySecurity.Decrypt(_cookie.Values.Get("CustomerEmail"), true);
                        _strName = MySecurity.Decrypt(_cookie.Values.Get("CustomerName"), true);
                        _strMobile = MySecurity.Decrypt(_cookie.Values.Get("CustomerMobile"), true);
                        hdnEmail.Value = _strEmail.ToString().Trim();
                        txtEmail.Text = _strEmail;
                        txtName.Text = _strName;
                        txtMobile.Text = _strMobile;
                        string _isaccept = "FALSE";
                        string[] _CK = _cookie.Value.Split('&');
                        if (_CK.Length > 3)
                        {
                            _isaccept = MySecurity.Decrypt(_cookie.Values.Get("IsAccept"), true);
                            if (_isaccept != null && _isaccept == "TRUE")
                            {
                                hdnIsAceept.Value = "TRUE";
                            }
                        }
                    }
                    else
                    {
                        hdnEmail.Value = "";
                        if (Session[CE.Global.General.UserEmail] != null)
                        {
                            hdnEmail.Value = Session[CE.Global.General.UserEmail].ToString();
                        }
                    }
                    _userId = GetCustomer(_strEmail);
                    if (_userId > 0)
                    {
                        UpdateDetails(_userId, _strEmail, _strName, _strMobile);
                        txtEmail.Text = _strEmail;
                        txtName.Text = _strName;
                        txtMobile.Text = _strMobile;
                    }
                }
                _cookie = Request.Cookies.Get("GGMobileQuote");
                hdnUserLoginStatus.Value = "0";
                if (_cookie != null)
                {
                    hdnUserLoginStatus.Value = "1";
                    string _isaccept = "FALSE";
                    string[] _CK = _cookie.Value.Split('&');
                    if (_CK.Length > 3)
                    {
                        _isaccept = MySecurity.Decrypt(_cookie.Values.Get("IsAccept"), true);
                        if (_isaccept != null && _isaccept == "TRUE")
                        {
                            hdnIsAceept.Value = "TRUE";
                        }
                    }
                }
                //if (hdnUserLoginStatus.Value == "0")
                //{
                //    Response.Redirect("promo-your-details.aspx?qid=" + hdnQuoteId.Value + "&cid=" + hdnCarId.Value + "&pid=" + hdnPolicyId.Value);
                //}

                if (Session[General.UserId] != null)
                {
                    Cache.Remove("CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString());
                }
                else
                {
                    Cache.Remove("CarResult" + Session[General.CarId].ToString());
                }
                int resultCalculatePremium = 0;
                CarPolicy _carpolicy = new CarPolicy();
                CarPolicyDB _carpolicydb = new CarPolicyDB();
                _carpolicy = _carpolicydb.GetCarPolicy(Convert.ToInt64(hdnCarId.Value), _userId);
                if (_carpolicy.NInfo5 == null || _carpolicy.NInfo5 == 0)
                {
                    if ((Session["IsFromAutoLogin"] == null) || (Session["IsFromAutoLogin"] != null && Session["IsFromAutoLogin"].ToString() != "1"))
                        resultCalculatePremium = CalculatePremiumCountResults();
                }
                else
                {
                    if (Session["IsFromAutoLogin"] == null || Session["IsFromAutoLogin"].ToString() != "1")
                    {
                        resultCalculatePremium = CalculatePremium();
                        #region Edit Change Class
                        hdnInsuranceType.Value = "10";
                        //if (Session["FROMCARDETAIL"] != null && Session["FROMCARDETAIL"].ToString() == "1")
                        //{
                        //    if (resultCalculatePremium == 0)
                        //    {
                        //        //CarPolicy _carpolicy = new CarPolicy();
                        //        //CarPolicyDB _carpolicydb = new CarPolicyDB();
                        //        if (Session[General.CarPolicyId] != null)
                        //        {
                        //            //CAR POLICY DETAILS
                        //            //Change to 2+
                        //            Int64 _refceuserid = 0;
                        //            Int64 _carid = 0;

                        //            if (Session[General.UserId] != null)
                        //            {
                        //                _refceuserid = Convert.ToInt64(Session[General.UserId].ToString());
                        //            }

                        //            if (Session[General.CarId] != null)
                        //            {
                        //                _carid = Convert.ToInt64(Session[General.CarId].ToString());
                        //            }

                        //            _carpolicy = _carpolicydb.GetCarPolicy(_carid, _refceuserid);
                        //            if (_carpolicy != null)
                        //            {
                        //                _carpolicy.InsuranceType = 21;
                        //                hdnInsuranceType.Value = "21";
                        //                if (_carpolicy.Deductible == -1 || _carpolicy.Deductible == 5000)
                        //                {
                        //                    _carpolicy.Deductible = 0;
                        //                }
                        //                _carpolicy.IsCTPL = false;
                        //                _carpolicy.IsAddDriver = false;
                        //                _carpolicy.NoOfDriver = 0;

                        //                CarDriverDB _cardriverdb = new CarDriverDB();
                        //                _cardriverdb.UpdateAllStatus(_carid, _refceuserid);
                        //                _cardriverdb = null;
                        //                Int64 _policyresult = 0;
                        //                _policyresult = _carpolicydb.Insert(_carpolicy);

                        //                resultCalculatePremium = CalculatePremium();
                        //            }
                        //        }
                        //    }
                        //}

                        #endregion
                    }
                }
                _carpolicy = null;
                _carpolicydb = null;
                GetTempResultTableTwo();
            }

        }
        else
        {
            Response.Redirect("promo-car-quote.aspx");
        }
    }

    private void SetCookies(string Email, string Name, string Mobile)
    {
        try
        {
            string _isAccept = "FALSE";
            if (hdnIsAceept.Value == "TRUE")
            {
                _isAccept = "TRUE";
            }
            HttpCookie _cookie = new HttpCookie("GGMobileQuote");
            _cookie.Values.Add("CustomerName", MySecurity.Encrypt(Server.HtmlEncode(Name.ToString().Trim()), true));
            _cookie.Values.Add("CustomerEmail", MySecurity.Encrypt(Server.HtmlEncode(Email.ToString().Trim()), true));
            _cookie.Values.Add("CustomerMobile", MySecurity.Encrypt(Server.HtmlEncode(Mobile.ToString().Trim()), true));
            _cookie.Values.Add("IsAccept", MySecurity.Encrypt(_isAccept, true));
            _cookie.Expires = DateTime.Now.AddDays(30);
            Response.Cookies.Add(_cookie);
        }
        catch (Exception Ex)
        {
            Ex = null;
        }
    }

    private Int64 GetCustomer(string CustomerEmail)
    {
        Int64 _retVal = 0;
        try
        {
            AccountDB _accountdb = new AccountDB();
            Account _account = _accountdb.GetUserAccount(CustomerEmail.ToLower(), 400);
            if (_account != null)
            {
                _retVal = _account.CEID;
                Session[CE.Global.General.UserId] = _account.CEID;
                Session[CE.Global.General.UserTypeId] = _account.UserTypeId;
                Session[CE.Global.General.UserEmail] = _account.Email;

                Profile _profile = new Profile();
                ProfileDB _profiledb = new ProfileDB();
                Contact _contact = new Contact();
                ContactDB _contactdb = new ContactDB();

                _contact = _contactdb.GetContact(_account.CEID);
                _profile = _profiledb.GetProfile(_account.CEID);

                if (_contact != null)
                {
                    Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                }
                else
                {
                    Session[CE.Global.General.UserPhoneNo] = null;
                }
                if (_profile != null)
                {
                    if (_profile.FirstName != null && _profile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = Server.HtmlDecode(_profile.FirstName) + " " + Server.HtmlDecode(_profile.SurName);
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = Server.HtmlDecode(_profile.SurName);
                    }
                    if (_profile.IsAcceptTC != null)
                    {
                        Session[CE.Global.General.IsAcceptTC] = "0";
                        if (_profile.IsAcceptTC == true)
                        {
                            Session[CE.Global.General.IsAcceptTC] = "1";
                        }
                    }
                }
            }
            return _retVal;
        }
        catch (Exception ex)
        {
            return 0;
        }
    }

    private void UpdateDetails(Int64 UserId, string Email, string Name, string Mobile)
    {
        SetCookies(Email, Name, Mobile);
        if (UserId > 0)
        {
            Int64 UserIdUpdate = 0;
            MyDatabase _dbUserIdUpdate = new MyDatabase();
            string _spNameUserIdUpdate = "sprocMobileRefCEUserIdUpdateSingleItem";

            SortedList _spListUserIdUpdate = new SortedList();
            _spListUserIdUpdate.Add("@CarId", Convert.ToInt64(hdnCarId.Value));
            _spListUserIdUpdate.Add("@CECarPolicyId", Convert.ToInt64(hdnPolicyId.Value));
            _spListUserIdUpdate.Add("@RefCEUserId", UserId);
            _spListUserIdUpdate.Add("@Info5", Server.HtmlEncode(Email.ToString().Trim()));
            _spListUserIdUpdate.Add("@Info6", Server.HtmlEncode(Mobile.ToString().Trim()));
            _spListUserIdUpdate.Add("@Info7", Server.HtmlEncode(Name.ToString().Trim()));

            object _retObjectUserIdUpdate = _dbUserIdUpdate.ExecuteSP(_spNameUserIdUpdate, _spListUserIdUpdate);
            UserIdUpdate = Convert.ToInt64(_retObjectUserIdUpdate);

            if (UserId > 0 && UserIdUpdate > 0)
            {
                MyDatabase _dbUpdate = new MyDatabase();
                string _spNameUpdate = "sprocMobileCarInquiryDetailsInsertUpdateSingleItem";

                SortedList _spListUpdate = new SortedList();
                _spListUpdate.Add("@MobileCarInquiryId", Convert.ToInt64(hdnQuoteId.Value));
                _spListUpdate.Add("@Name", Server.HtmlEncode(Name.ToString().Trim()));
                _spListUpdate.Add("@EmailAddress", Server.HtmlEncode(Email.ToString().Trim()));
                _spListUpdate.Add("@PhoneNumber", Server.HtmlEncode(Mobile.ToString().Trim()));
                _spListUpdate.Add("@RefCEUserId", UserId);
                _spListUpdate.Add("@Step", 3);
                object _retObjectUpdate = _dbUpdate.ExecuteSP(_spNameUpdate, _spListUpdate);
            }
        }
    }

    private Int32 CalculatePremium()
    {
        Int32 _result = 0;
        MyDatabase _db = new MyDatabase();
        SortedList _sPara = new SortedList();

        Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
        Int64 _userId = 0;
        if (Session[General.UserId] != null)
        {
            _userId = Convert.ToInt64(Session[General.UserId].ToString());
        }
        _sPara.Add("@CarId", _carId);
        _sPara.Add("@RefUserId", _userId);
        _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceClear]", _sPara);

        //select car detail
        _db = new MyDatabase();
        _sPara = new SortedList();
        DataTable _dt = new DataTable("tblModelBody");
        _sPara.Add("@CarId", Session[General.CarId].ToString());
        _sPara.Add("@RefCEUserId", _userId);
        _dt = _db.GetDataTableBySP("[sprocCarDetailTHSelectSingleItem]", _sPara);
        string[] makeName;
        makeName = _dt.Rows[0]["MakeModelDesc"].ToString().Split(' ');

        #region Hide Kawna 22 May 2014

        #region KawnaPackage
        //try
        //{
        //    if (IsKawnaCar(makeName[0]))
        //    {
        //        DataTable dtPackage = new DataTable();

        //        CarPolicy _carpolicy = new CarPolicy();
        //        CarPolicyDB _carpolicydb = new CarPolicyDB();
        //        _carpolicy = _carpolicydb.GetCarPolicy(_carId, _userId);
        //        string strProviderList = "";

        //        string strCarProvince = _carpolicy.ProvinceRegistration == "BKK" ? "1" : "79";
        //        string strDriverAge1 = "", strDriverAge2 = "";
        //        int DriverAge1 = 0, DriverAge2 = 0;
        //        if (_carpolicy.IsAddDriver == true)
        //        {
        //            CarDriverList _cardriverlist = new CarDriverList();
        //            CarDriverDB _cardriverdb = new CarDriverDB();
        //            _cardriverlist = _cardriverdb.GetCarDriverList(_carId, _userId);
        //            _cardriverdb = null;
        //            int _noOfDriver = _carpolicy.NoOfDriver;
        //            for (int i = 1; i <= _noOfDriver; i++)
        //            {
        //                CarDriver _cardriver = _cardriverlist[i - 1];
        //                if (i == 1)
        //                {
        //                    DriverAge1 = General.GetUTCDateTime().Year - _cardriver.DOB.Year;
        //                }
        //                else if (i == 2)
        //                {
        //                    DriverAge2 = General.GetUTCDateTime().Year - _cardriver.DOB.Year;
        //                }
        //            }
        //            _cardriverlist = null;

        //            if (DriverAge1 >= 18 && DriverAge1 <= 24)
        //                strDriverAge1 = "18";
        //            else if (DriverAge1 >= 25 && DriverAge1 <= 35)
        //                strDriverAge1 = "25";
        //            else if (DriverAge1 >= 36 && DriverAge1 <= 50)
        //                strDriverAge1 = "36";
        //            else if (DriverAge1 > 50)
        //                strDriverAge1 = "50";

        //            if (_noOfDriver == 2)
        //            {
        //                if (DriverAge2 >= 18 && DriverAge2 <= 24)
        //                    strDriverAge2 = "18";
        //                else if (DriverAge2 >= 25 && DriverAge2 <= 35)
        //                    strDriverAge2 = "25";
        //                else if (DriverAge2 >= 36 && DriverAge2 <= 50)
        //                    strDriverAge2 = "36";
        //                else if (DriverAge2 > 50)
        //                    strDriverAge2 = "50";
        //            }

        //        }

        //        HttpWebRequest request;
        //        string kawnaModel = GetKawnaModelValue(makeName[0], _dt.Rows[0]["CarModel"].ToString() + " " + String.Format("{0:0.0}", (Convert.ToInt32(_dt.Rows[0]["CC"]) * 0.001)) + "cc " + _dt.Rows[0]["Door"].ToString() + " Door");
        //        string tun = GetKawnaSingleSumInsured(makeName[0], kawnaModel, _dt.Rows[0]["ManufactYear"].ToString());
        //        if (tun == "0") tun = "";
        //        string url = _url + "?brand=" + makeName[0].ToString() + "&id_motor=" + kawnaModel.ToString() + "&yearcar=" + _dt.Rows[0]["ManufactYear"].ToString() + "&tun=" + tun + "&Yins=0&dee=0&country=" + strCarProvince + "&rgb=" + strCarProvince + "&paper=no&plantry=&oldinsure=&clame=" + (_carpolicy.IsClaimLastYear == false ? "ไม่มีเครม" : "มีเครม+ไม่มีคู่กรณี") + "&rabu=" + (_carpolicy.IsAddDriver == true ? "yes" : "") + "&old1=" + strDriverAge1 + "&old2=" + strDriverAge2 + "&t=submit";
        //        string responseBody = string.Empty;
        //        string requestBody = "";
        //        byte[] byteData = UTF8Encoding.UTF8.GetBytes(requestBody.ToString());
        //        request = (HttpWebRequest)HttpWebRequest.Create(url);
        //        request.ContentType = "application/xml;charset=utf-8";
        //        request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ENUS)";
        //        request.Accept = "*/*";
        //        request.Method = "POST";
        //        request.ContentLength = byteData.Length;
        //        System.Net.ServicePointManager.Expect100Continue = false;
        //        request.KeepAlive = false;

        //        string startTime = DateTime.Now.ToString("HH:mm:ss.ff tt dd/MM/yyyy");
        //        DateTime sTime = DateTime.Now;
        //        DataTable dtIns = new DataTable();
        //        DataSet ds = new DataSet();
        //        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        //        {
        //            ds.ReadXml(response.GetResponseStream());
        //        }
        //        dtPackage = ds.Tables["Pre"];
        //        DataTable dt = ds.Tables["INS"];
        //        dtIns = dt.Clone();
        //        dtIns = dt.Copy();

        //        // *** Start Join Table ***
        //        DataTable dtblResult = dtPackage.Clone();
        //        dtblResult.Columns.Add("InsName", typeof(string));
        //        dtblResult.Columns.Add("INS_Text", typeof(string));
        //        dtblResult.Columns.Add("PRE_IdIns", typeof(string));

        //        //get row data
        //        var rowData = from row1 in dtPackage.AsEnumerable()
        //                      join row2 in dtIns.AsEnumerable()
        //                      on row1["PRE_Id"] equals row2["PRE_Id"]
        //                      select row1.ItemArray.Concat(row2.ItemArray).ToArray();

        //        //Add row data to dtblResult
        //        foreach (object[] values in rowData)
        //            dtblResult.Rows.Add(values);

        //        //Change column name back to original
        //        dtblResult.Columns["INS_Text"].ColumnName = "INS";

        //        //Remove extra column from result
        //        dtblResult.Columns.Remove("PRE_IdIns");
        //        dtblResult.Columns.Add("PROPRICE", typeof(Double));
        //        dtPackage.Dispose();
        //        dtPackage = new DataTable();
        //        dtPackage = dtblResult.Clone();
        //        dtPackage.Columns["PRICE"].DataType = typeof(string);
        //        //dtPackage = dtblResult.Copy();
        //        foreach (DataRow row in dtblResult.Rows)
        //        {
        //            dtPackage.ImportRow(row);
        //        }

        //        dtblResult.Dispose();
        //        dtIns.Dispose();
        //        // *** End Join Table ***
        //        _db = new MyDatabase();
        //        _sPara = new SortedList();
        //        DataTable _dtPvdList = new DataTable();
        //        _dtPvdList = _db.GetDataTable("SELECT ProviderId FROM tblKawnaProvider WHERE ProviderCompanyId IS NOT NULL");

        //        foreach (DataRow dr in _dtPvdList.Rows)
        //        {
        //            if (strProviderList != null && strProviderList != "")
        //                strProviderList += ",";
        //            strProviderList += dr["ProviderId"];
        //        }
        //        var strExpr = " INS IN(" + strProviderList + ") ";

        //        if (_carpolicy.InsuranceType == 10 || _carpolicy.InsuranceType == 11)
        //            strExpr += " AND POTYPE = 'ป1' ";
        //        else if (_carpolicy.InsuranceType == 21)
        //            strExpr += " AND POTYPE = 'ป2+' ";
        //        else if (_carpolicy.InsuranceType == 31)
        //            strExpr += " AND POTYPE = 'ป3+' ";
        //        else if (_carpolicy.InsuranceType == 30)
        //            strExpr += " AND POTYPE = 'ป3' ";

        //        if (_carpolicy.GarageType > 0 && _carpolicy.InsuranceType != 30)
        //        {
        //            strExpr += " AND FIX = ";
        //            strExpr += _carpolicy.GarageType.ToString() != "1" ? "'ห้าง' " : "'อู่' ";
        //        }
        //        if (_carpolicy.InsuranceType != 30)
        //        {
        //            if (_carpolicy.Deductible == 0)
        //                strExpr += " AND (ODDD = '' OR ODDD IS NULL)";
        //            else if (_carpolicy.Deductible > 0)
        //                strExpr += " AND ODDD <> ''";
        //        }
        //        if (_carpolicy.InsuranceType == 30)
        //        {
        //            if (_carpolicy.IsCTPL == true)
        //                strExpr += " AND (CMI_INCLUDE = 'yes' )";
        //            else
        //                strExpr += " AND (CMI_INCLUDE <> 'yes' )";
        //        }
        //        var strSort = " PRICE ASC, TUN ASC ";
        //        DataView dv = new DataView(dtPackage);

        //        dv.RowFilter = strExpr;
        //        dv.Sort = strSort;

        //        var query = (from order in dv.ToTable().AsEnumerable()
        //                     group order by order["INS"] into grp
        //                     let fewItems = grp.Take(3).ToList()
        //                     select fewItems.CopyToDataTable());

        //        DataTable boundTable = new DataTable();
        //        boundTable = dv.ToTable().Clone();
        //        foreach (var rsv in query)
        //        {
        //            for (int i = 0; i < rsv.Rows.Count; i++)
        //                boundTable.ImportRow(rsv.Rows[i]);
        //        }
        //        foreach (DataRow drc in boundTable.Rows)
        //        {
        //            _db = new MyDatabase();
        //            _sPara = new SortedList();
        //            _sPara.Add("FromSource", "W");
        //            _sPara.Add("CarId", Convert.ToInt64(Session[General.CarId]));
        //            _sPara.Add("ProviderId", drc["INS"].ToString() != "" ? Convert.ToInt32(drc["INS"]) : 0);
        //            _sPara.Add("PackageId", drc["PACKID"].ToString() != "" ? Convert.ToInt32(drc["PACKID"]) : 0);
        //            _sPara.Add("PackageName", drc["PACKNAME"].ToString());
        //            _sPara.Add("TotalPremium", drc["PRICE"].ToString() != "" ? Convert.ToDouble(drc["PRICE"]) : 0.0);
        //            _sPara.Add("TotalVMI", drc["PRICE"].ToString() != "" ? Convert.ToDouble(drc["PRICE"]) : 0.0);
        //            _sPara.Add("IsIncludeCMI", drc["CMI_INCLUDE"].ToString() != "" ? true : false);
        //            _sPara.Add("TPPD", drc["TP"].ToString() != "" ? (Convert.ToInt64(drc["TP"].ToString().Replace(",", ""))) : 0);
        //            _sPara.Add("TPBIP", drc["BT"].ToString().ToString() != "" ? (Convert.ToInt64(drc["BT"].ToString().Replace(",", ""))) : 0);
        //            _sPara.Add("TPBIA", drc["BI"].ToString().ToString() != "" ? (Convert.ToInt64(drc["BI"].ToString().Replace(",", ""))) : 0);
        //            _sPara.Add("DEC", drc["ODDD"].ToString().Trim() != "" ? Convert.ToDouble(drc["ODDD"].ToString().Trim()) : 0);
        //            _sPara.Add("SumInsured", drc["TUN"].ToString() != "" ? Convert.ToInt64(drc["TUN"].ToString()) : 0);
        //            _sPara.Add("FireAndTheft", drc["FIRE"].ToString() != "" ? Convert.ToDouble(drc["FIRE"].ToString()) : 0.0);
        //            _sPara.Add("Theft", drc["TUN"].ToString() != "" ? Convert.ToInt64(drc["TUN"].ToString()) : 0);
        //            _sPara.Add("PADriver", drc["PA"].ToString() != "" ? (Convert.ToDouble(drc["PA"].ToString().Replace(",", ""))) : 0.0);
        //            _sPara.Add("PAPassenger", drc["PA"].ToString() != "" ? (Convert.ToDouble(drc["PA"].ToString().Replace(",", ""))) : 0.0);
        //            _sPara.Add("MED", drc["ME"].ToString() != "" ? (Convert.ToDouble(drc["ME"].ToString().Replace(",", ""))) : 0.0);
        //            _sPara.Add("BailBond", drc["BB"].ToString() != "" ? (Convert.ToDouble(drc["BB"].ToString().Replace(",", ""))) : 0.0);
        //            _sPara.Add("RefUserId", Convert.ToDouble(Session[General.UserId].ToString()));
        //            _sPara.Add("IsSpecialOffer", 0);
        //            _sPara.Add("IsFloodCover", drc["FLOOD"].ToString().Trim() != "" ? 1 : 0);
        //            _sPara.Add("GarageType", drc["FIX"].ToString().Trim() != "" && drc["FIX"].ToString().Trim() == "ห้าง" ? 1 : 0);
        //            _sPara.Add("CarType", _dt.Rows[0]["Body"].ToString());
        //            _sPara.Add("CarDoors", _dt.Rows[0]["Door"].ToString() != "" ? Convert.ToInt32(_dt.Rows[0]["Door"].ToString()) : 4);
        //            _sPara.Add("@PeopleCovered", drc["P"].ToString().Trim() != "" ? drc["P"].ToString().Trim() : "0");
        //            _result = _db.ExecuteNonSqlSP("[sprocKawnaSaveResultPackages]", _sPara);

        //        }
        //        return _result;
        //    }
        //}
        //catch { }

        #endregion
        ////====Test Web Service

        #endregion

        BKIDetailDB bki = new BKIDetailDB();
        try
        {
            BKICalculationWithTimeout(_carId, _userId);
        }
        catch
        {
        }
        _db = new MyDatabase();
        _sPara = new SortedList();
        _sPara.Add("@CarId", Session[General.CarId].ToString());
        _sPara.Add("@RefUserId", _userId);

        _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculation]", _sPara);

        return _result;
    }

    private Int32 CalculatePremiumCountResults()
    {
        int _result = 0;
        MyDatabase _db = new MyDatabase();
        SortedList _sPara = new SortedList();

        Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
        Int64 _userId = 0;
        if (Session[General.UserId] != null)
        {
            _userId = Convert.ToInt64(Session[General.UserId].ToString());
        }
        _sPara.Add("@CarId", Session[General.CarId].ToString());
        _sPara.Add("@RefUserId", _userId);

        _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceClear]", _sPara);

        //select car detail
        _db = new MyDatabase();
        _sPara = new SortedList();
        DataTable _dt = new DataTable("tblModelBody");
        _sPara.Add("@CarId", Session[General.CarId].ToString());
        _sPara.Add("@RefCEUserId", _userId);
        _dt = _db.GetDataTableBySP("[sprocCarDetailTHSelectSingleItem]", _sPara);
        string[] makeName;
        makeName = _dt.Rows[0]["MakeModelDesc"].ToString().Split(' ');

        if (_dt.Rows.Count > 0)
        {

            _db = new MyDatabase();
            _sPara = new SortedList();
            _sPara.Add("@CarId", Session[General.CarId].ToString());
            _sPara.Add("@RefUserId", _userId);

            BKIDetailDB bki = new BKIDetailDB();


            //====Test Web Service
            try
            {
                BKICalculationWithTimeout(_carId, _userId);
            }
            catch
            {
            }

            _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationWithResultCounting]", _sPara);

            return _result;
            //}
        }
        return 0;
    }

    protected void dlCarResults_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item ||
             e.Item.ItemType == ListItemType.AlternatingItem)
        {
            //ImageButton imgEmailQuote = (ImageButton)e.Item.FindControl("imgEmailQuote");
            //imgEmailQuote.Attributes.Add("onclick", "return confirm('Are you sure you want to send this quote?');");

            Label lblPackage = (Label)e.Item.FindControl("lblPackage");
            Label lblInsuranceClass = (Label)e.Item.FindControl("lblInsuranceClass");
            Label lblBhat = (Label)e.Item.FindControl("lblBhat");
            Label lblPremiumAmount = (Label)e.Item.FindControl("lblPremiumAmount");
            Label lblPromotionPrice = (Label)e.Item.FindControl("lblPromotionPrice");

            Label lblProviderCompanyName = (Label)e.Item.FindControl("lblProviderCompanyName");

            Label lblPlanName = (Label)e.Item.FindControl("lblPlanName");
            Label lblProviderCompanyID = (Label)e.Item.FindControl("lblProviderCompanyID");
            Label lblCarResultID = (Label)e.Item.FindControl("lblCarResultID");
            Image imgProviderCompanyLogo = (Image)e.Item.FindControl("imgProviderCompanyLogo");
            HtmlGenericControl divProvider = (HtmlGenericControl)(e.Item.FindControl("divProvider"));

            //Label lblSpecialNBC = (Label)e.Item.FindControl("lblSpecialNBC");
            //lblSpecialNBC.Text = "";
            lblBhat.Text = Resources.CarInsurance.Baht;
            string _promotionPrice = DataBinder.Eval(e.Item.DataItem, "PromotionPrice").ToString().Trim();
            string _premiumAmount = DataBinder.Eval(e.Item.DataItem, "AnnualPremium").ToString().Trim();

            //13 Apr 2015 - Songkran Promotion - Start
            //lblPremiumAmount.Text = "";
            //lblPromotionPrice.Text = Convert.ToSingle(_premiumAmount).ToString("#,000.00");
            lblPromotionPrice.Text = Convert.ToSingle(_promotionPrice).ToString("#,000.00"); //"(฿) " + 

            if (_promotionPrice != _premiumAmount)
            {
                lblPremiumAmount.Text = Convert.ToSingle(_premiumAmount).ToString("#,000.00"); //"(฿) " + 
            }
            //13 Apr 2015 - Songkran Promotion - End

            lblProviderCompanyID.Text = DataBinder.Eval(e.Item.DataItem, "ProviderCompanyId").ToString();
            //lblProviderCompanyName.Text = DataBinder.Eval(e.Item.DataItem, "CompanyName").ToString();
            lblPackage.Text = DataBinder.Eval(e.Item.DataItem, "PackageName").ToString();
            lblPlanName.Text = DataBinder.Eval(e.Item.DataItem, "PackageName").ToString();
            lblCarResultID.Text = DataBinder.Eval(e.Item.DataItem, "CITempResultID").ToString();

            //HyperLink hlnkView = (HyperLink)e.Item.FindControl("hlnkView");
            //hlnkView.NavigateUrl = "~/Quote_Result_Detail.aspx?crid=" + lblCarResultID.Text;

            //HyperLink hlnkViewTop = (HyperLink)e.Item.FindControl("hlnkViewTop");
            //hlnkViewTop.NavigateUrl = "~/Quote_Result_Detail.aspx?crid=" + lblCarResultID.Text;

            //Sakthi on 13 Nov 2014 - Start
            divProvider.Attributes.Add("class", getProviderLogoCss(lblProviderCompanyID.Text, "result"));
            //Literal imgSpecial = (Literal)e.Item.FindControl("lblSpecial");
            //System.Web.UI.HtmlControls.HtmlGenericControl divPrice = (System.Web.UI.HtmlControls.HtmlGenericControl)e.Item.FindControl("divbgimage");
            //if (lblPlanName.Text != "GluayGluay.com Special")
            //{
            //    imgProviderCompanyLogo.ImageUrl = "~" + DataBinder.Eval(e.Item.DataItem, "CompanyLogoServerUrl").ToString(); //"http://www.gluaygluay.com"
            //}
            //else
            //{
            //    lblSpecialNBC.Text = "<br/>" + Resources.CarInsurance.SpecialNCB;
            //    imgProviderCompanyLogo.ImageUrl = "~/images/public/gluaygluay.png";
            //    imgProviderCompanyLogo.AlternateText = "GluayGluay.com";
            //    imgSpecial.Text = "<img src='images/bg/special_offer.png' alt='Special Offer' style='border-width:0px' /><br />";
            //    divPrice.Attributes.Add("class", "right pricenotop");
            //}
            //Sakthi on 13 Nov 2014 - End

            if (lblCarResultID.Text.Trim() != "" && Session[General.UserId] != null && Session[General.CarId] != null)
            {
                #region More Details
                if (Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] != null)
                {
                    DataView dv = new DataView((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()]);

                    string _instype = DataBinder.Eval(e.Item.DataItem, "Info2").ToString().Trim();
                    Int32 InsType = 0;
                    if (!Int32.TryParse(_instype, out InsType))
                    {
                        InsType = 0;
                    }
                    lblInsuranceClass.Text = GetInsuranceTypeName(InsType);
                    string CITempResultId = lblCarResultID.Text.Trim();
                    dv.RowFilter = " CITempResultId in (" + CITempResultId + ")";
                    DataTable dtFiltered = dv.ToTable();
                    if (Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] != null)
                    {
                        if (dtFiltered.Rows.Count > 0)
                        {
                            int rowCount = dtFiltered.Rows.Count;

                            lblCarResultID.Text = CITempResultId;

                            for (int iRows = 0; iRows < rowCount; iRows++)
                            {
                                string _makemodel = "";
                                string _garagetype = "";
                                string _caryear = "";
                                string _ncb = "";
                                string _policystartdate = "";

                                Int64 _cecarid = 0;

                                if (Session[General.CarPolicyId] != null && Session[General.CarId] != null)
                                {
                                    _cecarid = Convert.ToInt64(Session[General.CarId]);
                                    Int64 _cepolicyid = Convert.ToInt64(Session[General.CarPolicyId]);
                                    Int64 _userId = 0;

                                    if (Session[General.UserId] != null)
                                    {
                                        _userId = Convert.ToInt64(Session[General.UserId].ToString());
                                    }

                                    CarDetailTH _cardetail = new CarDetailTH();
                                    CarDetailTHDB _cardetaildb = new CarDetailTHDB();
                                    _cardetail = _cardetaildb.GetCar(_cecarid, _userId);

                                    CarPolicy _carpolicy = new CarPolicy();
                                    CarPolicyDB _carpolicydb = new CarPolicyDB();
                                    _carpolicy = _carpolicydb.GetCarPolicy(_cecarid, _cepolicyid, _userId);

                                    if (_cardetail != null)
                                    {
                                        _makemodel = _cardetail.CarModelName.Replace('_', ' ') + " " + _cardetail.Body + " " + _cardetail.CC + "cc " + _cardetail.Door.ToString() + " doors";
                                        _caryear = _cardetail.ManufactYear.ToString();
                                    }

                                    if (_carpolicy != null)
                                    {
                                        _garagetype = _carpolicy.GarageType.ToString();
                                        _ncb = _carpolicy.NCDPercent.ToString();
                                        _policystartdate = _carpolicy.CoverageCommenceDate.ToString("dd/MMM/yyyy");
                                    }

                                    Label lblGarage = (Label)e.Item.FindControl("lblGarage");
                                    if (_garagetype.Trim() == "1")
                                        lblGarage.Text = Resources.CarInsurance.Garage_Authorized;
                                    else
                                        lblGarage.Text = Resources.CarInsurance.Garage_Dealer;

                                    Label lblMakeModel = (Label)e.Item.FindControl("lblMakeModel");
                                    Label lblCarYear = (Label)e.Item.FindControl("lblCarYear");
                                    //Label lblPolicyDate = (Label)e.Item.FindControl("lblPolicyDate");
                                    //Label lblNCB = (Label)e.Item.FindControl("lblNCB");
                                    //Label lblQuoteDate = (Label)e.Item.FindControl("lblQuoteDate");
                                    lblMakeModel.Text = _makemodel;
                                    lblCarYear.Text = _caryear;
                                    //lblPolicyDate.Text = _policystartdate;
                                    //lblNCB.Text = _ncb + "%";
                                    // lblQuoteDate.Text = General.GetUTCDateTime().ToString("dd/MMM/yyyy");
                                }
                                #region Label Declaration
                                //Label lblTitleRefNo = (Label)e.Item.FindControl("lblTitleRefNo");
                                Label lblTitleGarage = (Label)e.Item.FindControl("lblTitleGarage");
                                Label lblTitleMakeModel = (Label)e.Item.FindControl("lblTitleMakeModel");
                                Label lblTitleCarYear = (Label)e.Item.FindControl("lblTitleCarYear");
                                Label lblTitleExcess = (Label)e.Item.FindControl("lblTitleExcess");
                                Label lblTitleSumInsure = (Label)e.Item.FindControl("lblTitleSumInsure");
                                lblTitleGarage.Text = Resources.CarMenu.TitleGarage;
                                lblTitleMakeModel.Text = Resources.CarMenu.TitleMakeModel;
                                lblTitleCarYear.Text = Resources.CarMenu.TitleCarYear;
                                lblTitleExcess.Text = Resources.CarMenu.TitleExcess;
                                lblTitleSumInsure.Text = Resources.CarInsurance.SumInsured;
                                #endregion

                                //Label lblRefNo = (Label)e.Item.FindControl("lblRefNo");
                                string _providercompanyid = dtFiltered.Rows[iRows]["ProviderCompanyId"].ToString();
                                //lblRefNo.Text = General.GetReferenceNumber(_cecarid.ToString(), _providercompanyid, dtFiltered.Rows[iRows]["packagename"].ToString());


                                //Deductible- Excess
                                Label lblExcess = (Label)e.Item.FindControl("lblExcess");
                                String dec = string.Empty;
                                if (Convert.ToSingle(dtFiltered.Rows[iRows]["DEC"].ToString()) == 0)
                                {
                                    dec = Resources.CarInsuranceResultPage.Waived;
                                }
                                else
                                {
                                    dec = String.Format("{0:0,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["DEC"].ToString()));
                                }
                                lblExcess.Text = dec;
                                Label lblSumInsure = (Label)e.Item.FindControl("lblSumInsure");
                                lblSumInsure.Text = String.Format("{0:0,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["SumInsured"].ToString())) + " " + Resources.CarInsurance.Baht;
                            }

                        }
                    }
                }
                else if (Cache["CarResult" + Session[General.CarId].ToString()] != null)
                {
                    DataView dv = new DataView((DataTable)Cache["CarResult" + Session[General.CarId].ToString()]);

                    string _instype = DataBinder.Eval(e.Item.DataItem, "Info2").ToString().Trim();
                    Int32 InsType = 0;
                    if (!Int32.TryParse(_instype, out InsType))
                    {
                        InsType = 0;
                    }
                    lblInsuranceClass.Text = GetInsuranceTypeName(InsType);
                    string CITempResultId = lblCarResultID.Text.Trim();
                    dv.RowFilter = " CITempResultId in (" + CITempResultId + ")";
                    DataTable dtFiltered = dv.ToTable();
                    if (Cache["CarResult" + Session[General.CarId].ToString()] != null)
                    {
                        if (dtFiltered.Rows.Count > 0)
                        {
                            int rowCount = dtFiltered.Rows.Count;

                            lblCarResultID.Text = CITempResultId;

                            for (int iRows = 0; iRows < rowCount; iRows++)
                            {
                                string _makemodel = "";
                                string _garagetype = "";
                                string _caryear = "";
                                string _ncb = "";
                                string _policystartdate = "";

                                Int64 _cecarid = 0;

                                if (Session[General.CarPolicyId] != null && Session[General.CarId] != null)
                                {
                                    _cecarid = Convert.ToInt64(Session[General.CarId]);
                                    Int64 _cepolicyid = Convert.ToInt64(Session[General.CarPolicyId]);
                                    Int64 _userId = 0;

                                    if (Session[General.UserId] != null)
                                    {
                                        _userId = Convert.ToInt64(Session[General.UserId].ToString());
                                    }

                                    CarDetailTH _cardetail = new CarDetailTH();
                                    CarDetailTHDB _cardetaildb = new CarDetailTHDB();
                                    _cardetail = _cardetaildb.GetCar(_cecarid, _userId);

                                    CarPolicy _carpolicy = new CarPolicy();
                                    CarPolicyDB _carpolicydb = new CarPolicyDB();
                                    _carpolicy = _carpolicydb.GetCarPolicy(_cecarid, _cepolicyid, _userId);

                                    if (_cardetail != null)
                                    {
                                        _makemodel = _cardetail.CarModelName.Replace('_', ' ') + " " + _cardetail.Body + " " + _cardetail.CC + "cc " + _cardetail.Door.ToString() + " doors";
                                        _caryear = _cardetail.ManufactYear.ToString();
                                    }

                                    if (_carpolicy != null)
                                    {
                                        _garagetype = _carpolicy.GarageType.ToString();
                                        _ncb = _carpolicy.NCDPercent.ToString();
                                        _policystartdate = _carpolicy.CoverageCommenceDate.ToString("dd/MMM/yyyy");
                                    }

                                    Label lblGarage = (Label)e.Item.FindControl("lblGarage");
                                    if (_garagetype.Trim() == "1")
                                        lblGarage.Text = Resources.CarInsurance.Garage_Authorized;
                                    else
                                        lblGarage.Text = Resources.CarInsurance.Garage_Dealer;

                                    Label lblMakeModel = (Label)e.Item.FindControl("lblMakeModel");
                                    Label lblCarYear = (Label)e.Item.FindControl("lblCarYear");
                                    //Label lblPolicyDate = (Label)e.Item.FindControl("lblPolicyDate");
                                    //Label lblNCB = (Label)e.Item.FindControl("lblNCB");
                                    //Label lblQuoteDate = (Label)e.Item.FindControl("lblQuoteDate");
                                    lblMakeModel.Text = _makemodel;
                                    lblCarYear.Text = _caryear;
                                    //lblPolicyDate.Text = _policystartdate;
                                    //lblNCB.Text = _ncb + "%";
                                    // lblQuoteDate.Text = General.GetUTCDateTime().ToString("dd/MMM/yyyy");
                                }
                                #region Label Declaration
                                //Label lblTitleRefNo = (Label)e.Item.FindControl("lblTitleRefNo");
                                Label lblTitleGarage = (Label)e.Item.FindControl("lblTitleGarage");
                                Label lblTitleMakeModel = (Label)e.Item.FindControl("lblTitleMakeModel");
                                Label lblTitleCarYear = (Label)e.Item.FindControl("lblTitleCarYear");
                                Label lblTitleExcess = (Label)e.Item.FindControl("lblTitleExcess");
                                Label lblTitleSumInsure = (Label)e.Item.FindControl("lblTitleSumInsure");
                                lblTitleGarage.Text = Resources.CarMenu.TitleGarage;
                                lblTitleMakeModel.Text = Resources.CarMenu.TitleMakeModel;
                                lblTitleCarYear.Text = Resources.CarMenu.TitleCarYear;
                                lblTitleExcess.Text = Resources.CarMenu.TitleExcess;
                                lblTitleSumInsure.Text = Resources.CarInsurance.SumInsured;
                                #endregion

                                //Label lblRefNo = (Label)e.Item.FindControl("lblRefNo");
                                string _providercompanyid = dtFiltered.Rows[iRows]["ProviderCompanyId"].ToString();
                                //lblRefNo.Text = General.GetReferenceNumber(_cecarid.ToString(), _providercompanyid, dtFiltered.Rows[iRows]["packagename"].ToString());


                                //Deductible- Excess
                                Label lblExcess = (Label)e.Item.FindControl("lblExcess");
                                String dec = string.Empty;
                                if (Convert.ToSingle(dtFiltered.Rows[iRows]["DEC"].ToString()) == 0)
                                {
                                    dec = Resources.CarInsuranceResultPage.Waived;
                                }
                                else
                                {
                                    dec = String.Format("{0:0,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["DEC"].ToString()));
                                }
                                lblExcess.Text = dec;
                                Label lblSumInsure = (Label)e.Item.FindControl("lblSumInsure");
                                lblSumInsure.Text = String.Format("{0:0,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["SumInsured"].ToString())) + " " + Resources.CarInsurance.Baht;
                            }

                        }
                    }
                }
                #endregion
            }
            else if (lblCarResultID.Text.Trim() != "" && Session[General.CarId] != null) //13 Apr 2015 for Songkran's Promotion - Start
            {
                #region More Details
                if (Cache["CarResult" + Session[General.CarId].ToString()] != null)
                {
                    DataView dv = new DataView((DataTable)Cache["CarResult" + Session[General.CarId].ToString()]);

                    string _instype = DataBinder.Eval(e.Item.DataItem, "Info2").ToString().Trim();
                    Int32 InsType = 0;
                    if (!Int32.TryParse(_instype, out InsType))
                    {
                        InsType = 0;
                    }
                    lblInsuranceClass.Text = GetInsuranceTypeName(InsType);
                    string CITempResultId = lblCarResultID.Text.Trim();
                    dv.RowFilter = " CITempResultId in (" + CITempResultId + ")";
                    DataTable dtFiltered = dv.ToTable();
                    if (Cache["CarResult" + Session[General.CarId].ToString()] != null)
                    {
                        if (dtFiltered.Rows.Count > 0)
                        {
                            int rowCount = dtFiltered.Rows.Count;

                            lblCarResultID.Text = CITempResultId;

                            for (int iRows = 0; iRows < rowCount; iRows++)
                            {
                                string _makemodel = "";
                                string _garagetype = "";
                                string _caryear = "";
                                string _ncb = "";
                                string _policystartdate = "";

                                Int64 _cecarid = 0;

                                if (Session[General.CarPolicyId] != null && Session[General.CarId] != null)
                                {
                                    _cecarid = Convert.ToInt64(Session[General.CarId]);
                                    Int64 _cepolicyid = Convert.ToInt64(Session[General.CarPolicyId]);
                                    Int64 _userId = 0;

                                    if (Session[General.UserId] != null)
                                    {
                                        _userId = Convert.ToInt64(Session[General.UserId].ToString());
                                    }

                                    CarDetailTH _cardetail = new CarDetailTH();
                                    CarDetailTHDB _cardetaildb = new CarDetailTHDB();
                                    _cardetail = _cardetaildb.GetCar(_cecarid, _userId);

                                    CarPolicy _carpolicy = new CarPolicy();
                                    CarPolicyDB _carpolicydb = new CarPolicyDB();
                                    _carpolicy = _carpolicydb.GetCarPolicy(_cecarid, _cepolicyid, _userId);

                                    if (_cardetail != null)
                                    {
                                        _makemodel = _cardetail.CarModelName.Replace('_', ' ') + " " + _cardetail.Body + " " + _cardetail.CC + "cc " + _cardetail.Door.ToString() + " doors";
                                        _caryear = _cardetail.ManufactYear.ToString();
                                    }

                                    if (_carpolicy != null)
                                    {
                                        _garagetype = _carpolicy.GarageType.ToString();
                                        _ncb = _carpolicy.NCDPercent.ToString();
                                        _policystartdate = _carpolicy.CoverageCommenceDate.ToString("dd/MMM/yyyy");
                                    }

                                    Label lblGarage = (Label)e.Item.FindControl("lblGarage");
                                    if (_garagetype.Trim() == "1")
                                        lblGarage.Text = Resources.CarInsurance.Garage_Authorized;
                                    else
                                        lblGarage.Text = Resources.CarInsurance.Garage_Dealer;

                                    Label lblMakeModel = (Label)e.Item.FindControl("lblMakeModel");
                                    Label lblCarYear = (Label)e.Item.FindControl("lblCarYear");
                                    //Label lblPolicyDate = (Label)e.Item.FindControl("lblPolicyDate");
                                    //Label lblNCB = (Label)e.Item.FindControl("lblNCB");
                                    //Label lblQuoteDate = (Label)e.Item.FindControl("lblQuoteDate");
                                    lblMakeModel.Text = _makemodel;
                                    lblCarYear.Text = _caryear;
                                    //lblPolicyDate.Text = _policystartdate;
                                    //lblNCB.Text = _ncb + "%";
                                    // lblQuoteDate.Text = General.GetUTCDateTime().ToString("dd/MMM/yyyy");
                                }
                                #region Label Declaration
                                //Label lblTitleRefNo = (Label)e.Item.FindControl("lblTitleRefNo");
                                Label lblTitleGarage = (Label)e.Item.FindControl("lblTitleGarage");
                                Label lblTitleMakeModel = (Label)e.Item.FindControl("lblTitleMakeModel");
                                Label lblTitleCarYear = (Label)e.Item.FindControl("lblTitleCarYear");
                                Label lblTitleExcess = (Label)e.Item.FindControl("lblTitleExcess");
                                Label lblTitleSumInsure = (Label)e.Item.FindControl("lblTitleSumInsure");
                                lblTitleGarage.Text = Resources.CarMenu.TitleGarage;
                                lblTitleMakeModel.Text = Resources.CarMenu.TitleMakeModel;
                                lblTitleCarYear.Text = Resources.CarMenu.TitleCarYear;
                                lblTitleExcess.Text = Resources.CarMenu.TitleExcess;
                                lblTitleSumInsure.Text = Resources.CarInsurance.SumInsured;
                                #endregion

                                //Label lblRefNo = (Label)e.Item.FindControl("lblRefNo");
                                string _providercompanyid = dtFiltered.Rows[iRows]["ProviderCompanyId"].ToString();
                                //lblRefNo.Text = General.GetReferenceNumber(_cecarid.ToString(), _providercompanyid, dtFiltered.Rows[iRows]["packagename"].ToString());


                                //Deductible- Excess
                                Label lblExcess = (Label)e.Item.FindControl("lblExcess");
                                String dec = string.Empty;
                                if (Convert.ToSingle(dtFiltered.Rows[iRows]["DEC"].ToString()) == 0)
                                {
                                    dec = Resources.CarInsuranceResultPage.Waived;
                                }
                                else
                                {
                                    dec = String.Format("{0:0,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["DEC"].ToString()));
                                }
                                lblExcess.Text = dec;
                                Label lblSumInsure = (Label)e.Item.FindControl("lblSumInsure");
                                lblSumInsure.Text = String.Format("{0:0,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["SumInsured"].ToString())) + " " + Resources.CarInsurance.Baht;
                            }

                        }
                    }
                }
                #endregion
            } //13 Apr 2015 for Songkran's Promotion - End

        }
    }

    private void GetTempResultTableTwo()
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dtResult = new DataTable();
        string _spName = "[sprocCarInsuranceResultSelectItemList]";
        SortedList _sPara = new SortedList();
        _sPara.Add("@CarId", Session[General.CarId].ToString());

        if (Session["UserID"] != null)
        {
            _sPara.Add("@RefUserId", Session[General.UserId].ToString());
        }
        else
        {
            _sPara.Add("@RefUserId", 0);
        }

        _dtResult = _db.GetDataTableBySP(_spName, _sPara);

        if (Session[General.UserId] != null)
        {
            if (Session[General.CarId] != null)
            {
                Cache["CarResult" + Session[General.CarId].ToString()] = _dtResult;
                //Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] = _dtResult;
            }
        }
        else
        {
            if (Session[General.CarId] != null)
            {
                Cache["CarResult" + Session[General.CarId].ToString()] = _dtResult;
            }
        }

        CarDetailTH _cardetail = new CarDetailTH();
        CarDetailTHDB _cardetaildb = new CarDetailTHDB();
        if (Session[General.CarId] != null)
        {
            Int64 _longUserId = 0;
            if (Session[General.UserId] != null)
                _longUserId = Int64.Parse(Session[General.UserId].ToString());
            _cardetail = _cardetaildb.GetCar(Int64.Parse(Session[General.CarId].ToString()), _longUserId);
        }

        HttpCookie _cookie = Request.Cookies.Get("GGMobileQuote");
        if (_cookie != null)
        {
            lblAdvertiser.Text = "<img src=\"https://cv.accesstrade.in.th/cv.php?identifier=" + _cardetail.RowGUID + "&mcn=1f0e3dad99908345f7439f8ffabdffc4&result_id=100\" width=\"1\" height=\"1\" />";
        }
        if (_dtResult.DefaultView.Table.Rows.Count > 0)
        {
            DataTable _dtx = _dtResult.DefaultView.Table;
            foreach (DataRow dr in _dtx.Rows)
            {
                Int64 _discountResult = -1;
                DataTable _dt = new DataTable();
                MyDatabase _db2 = new MyDatabase();
                string strSQL = "SELECT dbo.fn_getPromotionPriceAssignPercentage(@ProviderCompanyId,@TotalPremium,10) ;";

                SortedList _sPara2 = new SortedList();
                _sPara2.Add("@ProviderCompanyId", Convert.ToInt32(dr["ProviderCompanyId"]));
                _sPara2.Add("@TotalPremium", dr["AnnualPremium"].ToString().Replace(",", ""));
                _discountResult = Convert.ToInt64(_db2.ExecuteScalarSqlStatement(strSQL, _sPara2));

                dr["PromotionPrice"] = _discountResult;
            }
        }

        dlCarResults.DataSource = null;
        dlCarResults.DataSource = _dtResult;
        dlCarResults.DataBind();

        divCallUs.Visible = false;
        divResults.Visible = true;
        hdnResults.Value = dlCarResults.Items.Count.ToString();
        if (dlCarResults.Items.Count <= 0)
        {
            divCallUs.Visible = true;
            divResults.Visible = false;
            //lblNoResultMessage.Text = "<div class='pad_10'><h2>" + Resources.CarMenu.NoMatchFound + "</h2><span class='font_12'><strong>" + Resources.CarMenu.TakeNote + ".</strong></span><div class='seperator'></div><div class='seperator'></div>" + Resources.CarMenu.ReturnOur + " <a href='/'>" + Resources.CarMenu.HomePage + "</a> " + Resources.CarMenu.OROur + " <a href='car-quote.aspx'>" + Resources.CarMenu.CarQuote + "</a> " + Resources.CarMenu.ForReQuote + "<div class='seperator'></div>" + Resources.CarMenu.ThanksUsing + "</div>";
        }
        else
        {
            if (Session["Language"] != null && Session["Language"].ToString() != "th-TH")
            {
                lblNoResultMessage.Text = "( " + dlCarResults.Items.Count + " ) packages found <br/><br/>";
            }
            else
            {
                lblNoResultMessage.Text = Resources.CarMenu.Package + " ( " + dlCarResults.Items.Count + " ) " + Resources.CarMenu.Found + " <br/><br/>";
            }
        }
    }

    protected void dlCarResults_ItemCommand(object source, DataListCommandEventArgs e)
    {
        try
        {
            if (((ImageButton)e.CommandSource).CommandName == "Email")
            {
                dlCarResults.SelectedIndex = e.Item.ItemIndex;
                Label lblCarResultID = (Label)e.Item.FindControl("lblCarResultID");
                //this.EmailQuote(lblCarResultID.Text);
                Label lblProviderCompanyID = (Label)e.Item.FindControl("lblProviderCompanyID");
                Response.Redirect("promo-email-confirm.aspx?rid=" + lblCarResultID.Text + "&prid=" + lblProviderCompanyID.Text + "&qid=" + hdnQuoteId.Value + "&cid=" + hdnCarId.Value + "&pid=" + hdnPolicyId.Value);
            }

            if (((ImageButton)e.CommandSource).CommandName == "Buy")
            {
                dlCarResults.SelectedIndex = e.Item.ItemIndex;
                Label lblCarResultID = (Label)e.Item.FindControl("lblCarResultID");
                Label lblProviderCompanyID = (Label)e.Item.FindControl("lblProviderCompanyID");
                Response.Redirect("promo-proposal-form.aspx?rid=" + lblCarResultID.Text + "&prid=" + lblProviderCompanyID.Text + "&qid=" + hdnQuoteId.Value + "&cid=" + hdnCarId.Value + "&pid=" + hdnPolicyId.Value);
            }

            if (((ImageButton)e.CommandSource).CommandName == "CallMe")
            {
                if (CheckCallMeCount() < 3)
                {
                    dlCarResults.SelectedIndex = e.Item.ItemIndex;
                    Label lblCarResultID = (Label)e.Item.FindControl("lblCarResultID");
                    Label lblProviderCompanyID = (Label)e.Item.FindControl("lblProviderCompanyID");
                    string strInsType = "10";
                    if (hdnInsuranceType.Value != null && hdnInsuranceType.Value != string.Empty)
                    {
                        strInsType = hdnInsuranceType.Value;
                    }
                    Response.Redirect("promo-call-me.aspx?rid=" + lblCarResultID.Text + "&prid=" + lblProviderCompanyID.Text + "&qid=" + hdnQuoteId.Value + "&cid=" + hdnCarId.Value + "&pid=" + hdnPolicyId.Value + "&instype=" + strInsType);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, this.GetType(), "alert", "alert('" + Resources.CarMenu.Callback3Times + "');", true);
                }
            }
        }
        catch (Exception ex)
        {
        }
    }

    #region kawna
    private string _url = "http://www.kawna.com/dat/qMotor2.php";
    DataSet dsBrand = new DataSet();
    private bool IsKawnaCar(string makeName)
    {
        MyDatabase _db = new MyDatabase();
        object _result = null;
        Int64 _retValue = 0;

        _result = _db.ExecuteScalarSqlStatement("select COUNT(CarModel)from tblKawnaCar WHERE  CarMake = '" + makeName + "' ");
        if (_result != null)
        {
            _retValue = Convert.ToInt64(_result);
        }
        return _retValue > 0;
    }

    DataSet dsModel = new DataSet();
    private string GetKawnaModelValue(string brandName, string modelName)
    {
        try
        {
            HttpWebRequest request;
            string url = _url + "?t=m&b=" + brandName;
            string responseBody = string.Empty;
            string requestBody = "";
            byte[] byteData = UTF8Encoding.UTF8.GetBytes(requestBody.ToString());
            request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.ContentType = "application/xml;charset=utf-8";
            request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ENUS)";
            request.Accept = "*/*";
            request.Method = "POST";
            request.ContentLength = byteData.Length;
            System.Net.ServicePointManager.Expect100Continue = false;
            request.KeepAlive = false;
            DataSet dsM = new DataSet();
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                dsM.ReadXml(response.GetResponseStream());
            }
            foreach (DataRow dr in dsM.Tables[0].Rows)
            {
                if (dr["M_Text"].ToString().ToLower() == modelName.ToLower())
                    return dr["value"].ToString();
            }
        }
        catch { }

        MyDatabase _db = new MyDatabase();
        DataTable dtKawnaCar = new DataTable();
        dtKawnaCar = _db.GetDataTable("select Distinct CarModelID from tblKawnaCar WHERE CarMake = '" + brandName + "' AND CarModel = '" + modelName + "' ");
        if (dtKawnaCar.Rows.Count > 0)
            return dtKawnaCar.Rows[0]["CarModelID"].ToString();

        return "";
    }
    /// <summary>
    /// Get Minimum Kawna SumInsured
    /// </summary>
    /// <param name="cmake"></param>
    /// <param name="cmodel"></param>
    /// <param name="cyear"></param>
    /// <returns></returns>
    private string GetKawnaSingleSumInsured(string cmake, string cmodel, string cyear)
    {
        if (cmake == "" || cmodel == "" || cyear == "")
            return "";

        try
        {
            HttpWebRequest request;
            string url = _url + "?t=t&b=" + cmake.Trim() + "&m=" + cmodel.Trim() + "&y=" + cyear.Trim();
            string responseBody = string.Empty;
            string requestBody = "";
            byte[] byteData = UTF8Encoding.UTF8.GetBytes(requestBody.ToString());
            request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.ContentType = "application/xml;charset=utf-8";
            request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ENUS)";
            request.Accept = "*/*";
            request.Method = "POST";
            request.ContentLength = byteData.Length;
            System.Net.ServicePointManager.Expect100Continue = false;
            request.KeepAlive = false;

            DataSet dsS = new DataSet();
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                dsS.ReadXml(response.GetResponseStream());
            }

            if (dsS.Tables[0].Rows.Count == 1 && dsS.Tables[0].Rows[0][0].ToString() == "ERR4")
            {

            }
            else
            {
                return dsS.Tables[0].Rows[0][0].ToString();
            }
        }
        catch { }

        MyDatabase _db = new MyDatabase();
        DataTable dtKawnaCar = new DataTable();
        dtKawnaCar = _db.GetDataTable("select SumInsured from tblKawnaCar WHERE CarMake = '" + cmake + "' AND CarModelID = " + cmodel + " And Year = " + cyear + " ");
        if (dtKawnaCar.Rows.Count > 0)
            return dtKawnaCar.Rows[0]["SumInsured"].ToString();

        return "";
    }

    private double GetPromotionPrice(double price, int knInsurerId)
    {

        double _ret = 0;
        if (knInsurerId != 61 && knInsurerId != 2 && price >= 5000.00)
        {
            try
            {
                double netPremium = Math.Floor(Math.Round(price / 1.07, 0) / 1.004);
                double discount = netPremium * 5 / 100;
                double duty = Math.Ceiling(netPremium * 0.004);
                double vat = (netPremium + duty) * 0.07;
                _ret = netPremium - discount + duty + vat;
            }
            catch { }
        }
        return _ret;

    }

    #endregion

    protected void btnNewQuote_Click(object sender, EventArgs e)
    {
        CE.Global.General.ClearAllSession(this.Page, "CI");
        Response.Redirect("promo-car-quote.aspx");
    }

    private void EmailQuote(string carresultid)
    {
        string qs_carselected = carresultid;
        string _makemodel = "";
        string _garagetype = "";
        string _caryear = "";
        string _ncb = "";
        string _policystartdate = "";
        string _userfirstname = "";

        Int64 _cecarid = 0;

        if (Session[General.CarPolicyId] != null && Session[General.CarId] != null)
        {
            _cecarid = Convert.ToInt64(Session[General.CarId]);
            Int64 _cepolicyid = Convert.ToInt64(Session[General.CarPolicyId]);
            Int64 _userId = 0;

            if (Session[General.UserId] != null)
            {
                _userId = Convert.ToInt64(Session[General.UserId].ToString());
            }

            CE.User.Profile usrprofile = new Profile();
            ProfileDB usrprofiledb = new ProfileDB();

            usrprofile = usrprofiledb.GetProfile(_userId);
            if (usrprofile != null)
            {
                _userfirstname = usrprofile.FirstName;
            }

            CarDetailTH _cardetail = new CarDetailTH();
            CarDetailTHDB _cardetaildb = new CarDetailTHDB();
            _cardetail = _cardetaildb.GetCar(_cecarid, _userId);

            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            _carpolicy = _carpolicydb.GetCarPolicy(_cecarid, _cepolicyid, _userId);

            if (_cardetail != null)
            {
                if (_cardetail.MakeModelDesc != null && _cardetail.MakeModelDesc != "")
                    _makemodel = _cardetail.MakeModelDesc;
                else
                    _makemodel = _cardetail.CarModelName + " " + _cardetail.Body + " " + _cardetail.CC + "cc " + _cardetail.Door.ToString() + " doors";
                _caryear = _cardetail.ManufactYear.ToString();

                _makemodel = _makemodel.Replace("_", " ");
            }

            if (_carpolicy != null)
            {
                if (_carpolicy.GarageType.ToString().Trim() == "1")
                    _garagetype = Resources.CarInsurance.Garage_Authorized;
                else
                    _garagetype = Resources.CarInsurance.Garage_Dealer;

                _ncb = _carpolicy.NCDPercent.ToString();
                _policystartdate = _carpolicy.CoverageCommenceDate.ToString("dd/MMM/yyyy");
            }
        }

        string _refno = "";
        string _companyName = "";
        string _insurerimageurl = "";
        string _package = "";
        string _annualprice = "";
        string _excess = "";
        string _promotionprice = "";

        bool _isDamageShowImage = false;
        string _damage = "0";
        bool _isFireShowImage = false;
        string _fire = "0";
        bool _isTheftShowImage = false;
        string _theft = "0";
        string _medicalexp = "";
        string _losspe = "";
        string _lossuse = "";
        string _padriver = "";
        string _tppd = "";
        string _bailbond = "";
        string _providercompanyid = "";
        bool _isFloodCovered = false;

        if (qs_carselected != "" && Session[General.UserId] != null && Session[General.CarId] != null)
        {
            if (Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] != null)
            {
                DataView dv = new DataView((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()]);



                string CITempResultId = qs_carselected;

                dv.RowFilter = " CITempResultId in (" + CITempResultId + ")";
                DataTable dtFiltered = dv.ToTable();
                if (Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] != null)
                {
                    if (dtFiltered.Rows.Count > 0)
                    {
                        int rowCount = dtFiltered.Rows.Count;

                        for (int iRows = 0; iRows < rowCount; iRows++)
                        {
                            _providercompanyid = dtFiltered.Rows[iRows]["ProviderCompanyId"].ToString();
                            _refno = General.GetReferenceNumber(_cecarid.ToString(), _providercompanyid, dtFiltered.Rows[iRows]["packagename"].ToString());

                            if (dtFiltered.Rows[iRows]["packagename"].ToString() != "GluayGluay.com Special")
                            {
                                if (Session["Language"] != null)
                                {
                                    if (Session["Language"].ToString() == "th-TH")
                                        _companyName = General.GetProviderName(int.Parse(_providercompanyid), "1");
                                    else
                                        _companyName = General.GetProviderName(int.Parse(_providercompanyid), "2");
                                }
                                else
                                {
                                    //english
                                    _companyName = General.GetProviderName(int.Parse(_providercompanyid), "2");
                                }

                                _insurerimageurl = System.Configuration.ConfigurationSettings.AppSettings["TH.MobileUrl"].ToString() + CE.Global.General.GetProviderCompanyLogo(_providercompanyid); //"http://www.gluaygluay.com/"
                            }
                            else
                            {
                                _companyName = "";

                                _insurerimageurl = System.Configuration.ConfigurationSettings.AppSettings["TH.MobileUrl"].ToString() + "/images/public/logo/gluaygluay_logo.png";
                            }

                            _package = dtFiltered.Rows[iRows]["packagename"].ToString();


                            if (Convert.ToSingle(dtFiltered.Rows[iRows]["annualpremium"]) != Convert.ToSingle(dtFiltered.Rows[iRows]["promotionprice"]))
                            {
                                _annualprice = "<s>" + String.Format("{0:0,0.00}", Convert.ToSingle(dtFiltered.Rows[iRows]["annualpremium"].ToString())) + " " + Resources.CarInsurance.Baht + "</s>";
                            }

                            _annualprice = _annualprice + "<div style='color:#F00;font-size:20px;font-weight:bold;' >";
                            _annualprice = _annualprice + String.Format("{0:0,0.00}", Convert.ToSingle(dtFiltered.Rows[iRows]["promotionprice"].ToString())); //"999.00";
                            _annualprice = _annualprice + "</div>";

                            _annualprice = dtFiltered.Rows[iRows]["annualpremium"].ToString();
                            _promotionprice = dtFiltered.Rows[iRows]["promotionprice"].ToString();

                            _excess = String.Format("{0:0,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["DEC"].ToString()));

                            if (Convert.ToSingle(dtFiltered.Rows[iRows]["SumInsured"].ToString()) == 0)
                            {
                                _isDamageShowImage = true;
                            }
                            else
                            {
                                _damage = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["SumInsured"].ToString()));
                            }


                            if (Convert.ToInt32(dtFiltered.Rows[iRows]["Fire"].ToString()) == 0)
                                _isFireShowImage = true;
                            else
                                _fire = String.Format("{0:#,0}", Convert.ToInt32(dtFiltered.Rows[iRows]["Fire"].ToString()));

                            //Theft
                            if (Convert.ToSingle(dtFiltered.Rows[iRows]["Theft"].ToString()) == 0)
                                _isTheftShowImage = true;
                            else
                                _theft = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["Theft"].ToString()));

                            _tppd = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["TPPD"].ToString()));

                            _losspe = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["TPBIA"].ToString()));

                            _lossuse = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["TPBIP"].ToString()));

                            _padriver = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["PADriver"].ToString()));

                            _medicalexp = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["MedicalExpense"].ToString()));

                            _bailbond = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["BailBond"].ToString()));

                            if (dtFiltered.Rows[iRows]["IsFloodCover"].ToString() != "0")
                            {
                                _isFloodCovered = true;
                            }
                        }
                    }
                }
            }
        }
        string _emailList = "", _title = "";
        System.Text.StringBuilder _message = new System.Text.StringBuilder();
        if (hdnEmail.Value != null)
        {
            _emailList = hdnEmail.Value;
        }
        else
        {
            _emailList = Session[CE.Global.General.UserEmail].ToString();
        }
        _title = "";

        _title = "<mobile> GluayGluay.com: " + Resources.EmailMessage.EmailThisTitle + " " + _userfirstname + " (Quotation number : " + _refno + ")";


        string _strCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("Mobile.IsCXLive");
        string _mailBody = "";
        string domainUrl = "";
        Uri myUri = new Uri(HttpContext.Current.Request.Url.ToString());
        domainUrl = "http://www.gluaygluay.com/mobile";
        if (_strCXLive == "0")
        {
            domainUrl = "http://test.gluaygluay.com.gluaygluay.info/mobile";
        }

        #region "Mail Body"

        #region Header
        _mailBody = "<html>";
        _mailBody += "<head>";
        _mailBody += "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />";
        _mailBody += "<title>GluayGluay</title>";
        _mailBody += "<style>";

        _mailBody += ".body {";
        _mailBody += "margin-left: 0px;";
        _mailBody += "margin-top: 0px;";
        _mailBody += "margin-right: 0px;";
        _mailBody += "margin-bottom: 0px;";
        _mailBody += "font-family: Arial, sans-serif;";
        _mailBody += "font-size: 14px;";
        _mailBody += "color: #000000;";
        _mailBody += "background-repeat: repeat-x;";
        _mailBody += "background-color: #fff;";
        _mailBody += "text-decoration: none;}";

        _mailBody += "</style>";
        _mailBody += "</head>";
        #endregion

        _mailBody += "<body class='body'>";
        _mailBody += "<table width='800' border='0' align='center' cellpadding='0' cellspacing='0' style='line-height:20px;font-size:14px;'>";
        _mailBody += "<tr>";
        _mailBody += "<td height='1474' valign='top'>";
        _mailBody += "<table width='800' height='100' border='0' cellspacing='0' cellpadding='0'>";
        _mailBody += "<tr>";
        _mailBody += "<td><span class='email-banner'><img src='" + domainUrl + "/images/email-header.jpg' width='800' height='100' alt='' /></span></td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "<br />";

        #region Thank you
        _mailBody += "<table width='329' border='0' cellspacing='0' cellpadding='0'>";
        _mailBody += "<tr>";
        _mailBody += "<td width='329'><strong>" + Resources.EmailMessage.EmailThisHeader + "</strong></td>";
        _mailBody += "</tr>";
        _mailBody += "<tr>";
        _mailBody += " <td>" + Resources.Proposal.ThankYou + "</td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "<br />";
        #endregion

        #region Car Details
        _mailBody += "<table width='700' border='0' cellspacing='0' cellpadding='0'>";
        _mailBody += "<tr>";
        _mailBody += "<td valign='top' bgcolor='#C1C1C1'>";
        _mailBody += "<br />";
        _mailBody += "<table width='800' border='0' cellspacing='1' cellpadding='1'>";
        //_mailBody += "<tr>";
        //_mailBody += "<td height='26' colspan='4' bgcolor='#E7E7E7'>";
        //_mailBody += "<span style='font-size: 14px; font-weight: bold; padding-left: 10px; padding-bottom: 5px;";
        //_mailBody += "padding-top: 5px;'>" + Resources.Proposal.OrderNo + " " + _refNo + "</span>";
        //_mailBody += "</td>";
        //_mailBody += "</tr>";
        _mailBody += "<tr>";
        _mailBody += "<td width='150' height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.CarYear + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td width='363' height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _caryear + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td width='148' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.NCB + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td width='126' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _ncb + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.MakeModel + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='30' colspan='3' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _makemodel + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.GarageType + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td colspan='3' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _garagetype + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "<br />";
        #endregion


        bool IsGGSpecial = false;
        //logo
        string logourl = "";
        string package = _package;
        if (_package != "GluayGluay.com Special")
        {
            logourl = domainUrl + CE.Global.General.GetProviderCompanyLogo(_providercompanyid);
        }
        else
        {
            //[Yui] @13/09/2013
            IsGGSpecial = true;
            // --- End ---

            logourl = domainUrl + "/images/gg-logo/gluaygluay-logo.png";
            package += " (" + Resources.CarInsuranceResultPage.SpecialNCB + ")";
        }

        #region Main body

        #region Not Using
        float _fMonthlyPremiumAmount = Convert.ToSingle(_annualprice) / 4;
        string monthlyInstallment = "";

        if (_fMonthlyPremiumAmount > 0.0f)
        {
            string _monthlyPremiumAmount = String.Format("{0:0,0.00}", _fMonthlyPremiumAmount);
            monthlyInstallment = _monthlyPremiumAmount + "/mth<br/>";
        }
        else
        {
            monthlyInstallment = "<img src='" + domainUrl + "/images/icons/error.png' width='16' alt='NA' />";
        }
        #endregion

        _mailBody += "<table width='800' border='0' cellspacing='0' cellpadding='0'>";
        _mailBody += "<tr>";
        _mailBody += "<td height='129' valign='top'>";
        _mailBody += "<table width='520' border='0' cellspacing='1' cellpadding='1' bgcolor='#C1C1C1'>";

        #region Provider Logo & Package name
        _mailBody += "<tr>";
        _mailBody += "<td height='25' colspan='2' bgcolor='#FFFFFF' align='center'>";
        _mailBody += "<span style='padding: 10px;'>";
        _mailBody += "<img src='" + logourl + "' alt='' /></span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "<tr>";
        _mailBody += "<td width='324' height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.ProposalForm.Package + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td width='193' height='25' bgcolor='#E7E7E7' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += package + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region Deductible
        float _fDEC = 0.0f;//Convert.ToSingle(_excess.Replace(",",""));
        if (!float.TryParse(_excess.Replace(",", ""), out _fDEC))
        {
            _fDEC = 0.0f;
        }
        string deductible = "";
        if (_fDEC > 0.0f)
        {
            deductible = String.Format("{0:0,0.00}", _fDEC);
        }
        else
        {
            deductible = Resources.CarInsuranceResultPage.Waived;
        }
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.DEC + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += deductible + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region Own Damage
        string suminsured = "0";// String.Format("{0:#,0}", Convert.ToSingle(_damage.Replace(",", "")));
        float _flsuminsured = 0.0f;
        if (!float.TryParse(_damage.Replace(",", ""), out _flsuminsured))
        {
            _flsuminsured = 0.0f;
        }
        suminsured = String.Format("{0:#,0}", _flsuminsured);
        if (_flsuminsured == 0)
        {
            suminsured = "<img src='" + domainUrl + "/images/icons/error.png' width='16' alt='NA' />";
        }
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.OwnDamage + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += suminsured + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region Fire
        string fire = "0";// String.Format("{0:#,0}", Convert.ToSingle(_fire.Replace(",", "")));
        float _flfire = 0.0f;
        if (!float.TryParse(_fire.Replace(",", ""), out _flfire))
        {
            _flfire = 0.0f;
        }
        fire = String.Format("{0:#,0}", _flfire);
        if (_flfire == 0)
        {
            fire = "<img src='" + domainUrl + "/images/icons/error.png' width='16' alt='NA' />";
        }
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.Fire + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += fire + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region Theft
        string theft = "0";// String.Format("{0:#,0}", Convert.ToSingle(_theft.Replace(",", "")));
        float _fltheft = 0.0f;
        if (!float.TryParse(_theft.Replace(",", ""), out _fltheft))
        {
            _fltheft = 0.0f;
        }
        theft = String.Format("{0:#,0}", _fltheft);
        if (_fltheft == 0)
        {
            theft = "<img src='" + domainUrl + "/images/icons/error.png' width='16' alt='NA' />";
        }
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.Theft + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += theft + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region TPPD
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.TPPD + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _tppd + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region TPBIA
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.TPBIA + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _losspe + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region TPBIP
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.TPBIP + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _lossuse + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region PA Driver
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.PADriver + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _padriver + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region Medical Expense
        int _MedicalExpense = 0;// Convert.ToInt32(_medicalexp.Replace(",", ""));
        if (int.TryParse(_medicalexp.Replace(",", ""), out _MedicalExpense))
        {
            _MedicalExpense = 0;
        }
        string medicalExpense = "";
        if (_MedicalExpense == 0)
        {
            medicalExpense = "<img src='" + domainUrl + "/images/icons/error.png' width='16' alt='NA' />";
        }
        else
        {
            medicalExpense = String.Format("{0:#,0}", Convert.ToSingle(_MedicalExpense.ToString()));
        }
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.MED + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += medicalExpense + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region Bail Bond
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.BailBond + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _bailbond + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region Premium (+taxes & duties)
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.TotalVMI + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF' style='text-align:right;'>";

        //Sakthi on 10 Nov 2014 - Start
        if (Convert.ToSingle(_annualprice) != Convert.ToSingle(_promotionprice))
        {
            _mailBody += "<span style='font-size: 16px; text-decoration: line-through; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += String.Format("{0:0,0.00}", Convert.ToSingle(_annualprice)) + " " + Resources.CarInsurance.Baht + "</span><br />";
        }
        _mailBody += "<span style='font-size: 20px; color: #3A5999; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += String.Format("{0:0,0.00}", Convert.ToSingle(_promotionprice)) + " " + Resources.CarInsurance.Baht + "</span>";
        //if (_isCTPL == "No")
        //{
        //    if (Convert.ToSingle(dtResults.Rows[0]["annualpremium"].ToString()) != Convert.ToSingle(dtResults.Rows[0]["PromotionPrice"]))
        //    {
        //        _mailBody += "<span style='font-size: 16px; text-decoration: line-through; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        //        _mailBody += String.Format("{0:0,0.00}", Convert.ToSingle(dtResults.Rows[0]["annualpremium"].ToString())) + "</span><br />";
        //    }
        //    _mailBody += "<span style='font-size: 20px; color: #3A5999; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        //    _mailBody += String.Format("{0:0,0.00}", Convert.ToSingle(dtResults.Rows[0]["PromotionPrice"].ToString())) + "</span>";
        //}
        //else
        //{
        //    _mailBody += "<span style='font-size: 20px; color: #3A5999; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        //    _mailBody += String.Format("{0:0,0.00}", Convert.ToSingle(_Premium)) + "</span>";
        //}
        //Sakthi on 10 Nov 2014 - End
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        _mailBody += "</table>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "<br />";
        #endregion

        _mailBody += "<table style='line-height: 20px;' width='800' border='0' cellspacing='0' cellpadding='0'>";
        _mailBody += "<tr>";
        _mailBody += "<td width='787' height='26' colspan='4' bgcolor='#FFFFFF'>";

        #region Remarks
        _mailBody += "<a href='tel:022688222'><img src='" + domainUrl + Resources.EmailMessage.HotlineBanner + "' alt='Call Us at 02 268 8222' width='270' border='0' /></a>";
        _mailBody += "<br /><br /><br />";

        //_message.Append("<strong>Remarks</strong><br />");
        _mailBody += "<strong>" + Resources.ProposalForm.Remarks + "</strong><br />";
        //_message.Append("1 - The quotation valid for 7 days and subject to change without notice according to policy of company<br />");
        _mailBody += Resources.ProposalForm.RemarkOne + "<br />";
        //_message.Append("2- Premium and coverage are subject to underwriting criteria of insurance company.<br />");
        _mailBody += Resources.ProposalForm.RemarkTwo + "<br />";

        _mailBody += "<hr />";

        _mailBody += Resources.ProposalForm.ThisQuoteis + "<br />";
        //_mailBody += "<i>" + Resources.ProposalForm.EmailDisclaimer + "</i>";
        //_mailBody += "This Quote is subject to the insurer's final confirmation and coverage is only effective";
        //_mailBody += "when the";
        //_mailBody += "<br />";
        //_mailBody += "insurer has accepted the risk.";
        #endregion

        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "<hr />";

        #region Footer

        _mailBody += "<table style='line-height: 20px;' width='800' border='0' cellspacing='0' cellpadding='0'>";
        _mailBody += "<tr>";
        _mailBody += "<td colspan='2' valign='top'>";
        _mailBody += "<strong>" + Resources.WelcomeEmail.CompanyAdd1 + "</strong><br />";
        _mailBody += Resources.WelcomeEmail.CompanyAdd2 + "<br />";
        _mailBody += Resources.WelcomeEmail.CompanyAdd3 + "<br />";
        _mailBody += Resources.WelcomeEmail.CompanyAdd4 + "<br />";
        _mailBody += Resources.WelcomeEmail.CompanyPhone + "<br />";
        _mailBody += Resources.WelcomeEmail.CompanyFax + "<br />";
        _mailBody += Resources.WelcomeEmail.CompanyEmail + "<br />";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "<br />";

        _mailBody += "<table width='300' border='0' align='center' cellpadding='0' cellspacing='0'>";
        _mailBody += "<tr>";
        _mailBody += "<td width='44' style='text-align: center'>";
        _mailBody += "<a href='https://www.facebook.com/GGmotor' target='_blank'><img src='" + domainUrl + "/images/icons/fb-big.png' width='44' height='42'></a>";
        _mailBody += "</td>";
        _mailBody += "<td width='44' style='text-align: center'>";
        _mailBody += "<a href='https://plus.google.com/+Gluaygluay/posts' target='_blank'><img src='" + domainUrl + "/images/icons/g-plus-big.png' width='44' height='42'></a>";
        _mailBody += "</td>";
        _mailBody += "<td width='44' style='text-align: center'>";
        _mailBody += "<a href='http://www.youtube.com/channel/UCZ4gMtlXymBHxvcXO2cR1vA' target='_blank'><img src='" + domainUrl + "/images/icons/youtube-big.png' width='44' height='42'></a>";
        _mailBody += "</td>";
        _mailBody += "<td width='44' style='text-align: center'>";
        _mailBody += "<a href='http://iconosquare.com/ggmotor' target='_blank'><img src='" + domainUrl + "/images/icons/instagram-big.png' width='44' height='42'></a>";
        _mailBody += "</td>";
        _mailBody += "<td width='43' style='text-align: center'>";
        _mailBody += "<a href='http://www.linkedin.com/company/-com-gluaygluay-com-' target='_blank'><img src='" + domainUrl + "/images/icons/linkedin-big.png' width='44' height='42'></a>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";

        _mailBody += "<hr />";
        _mailBody += "<table style='line-height: 20px;' width='800' border='0' cellspacing='0' cellpadding='0' background='" + domainUrl + "/images/email-footer.jpg'>";
        _mailBody += "<tr>";
        _mailBody += "<td height='49'><br><p style='text-align: center'>© 2015 gluaygluay.com. All rights reserved.<br>";
        _mailBody += Resources.EmailMessage.AutoEmail + "</p></td>";
        _mailBody += "</tr>";
        _mailBody += "</table></td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "</body>";
        _mailBody += "</html>";
        #endregion

        #endregion

        if (MyMailManager.SendNotification(_emailList, _title, _mailBody))
        {
            Response.Redirect("email-confirm.aspx?type=email&resultid=" + carresultid + "&qid=" + hdnQuoteId.Value + "&cid=" + hdnCarId.Value + "&pid=" + hdnPolicyId.Value);
        }
        else
        {
            lblNoResultMessage.Text = Resources.CarMenu.EmailError;// "Cannot send mail quote please try again.";
        }

    }

    protected void BKICalculationWithTimeout(long _carId, long _userId)
    {
        BKIDetailDB bki = new BKIDetailDB();

        System.Threading.Thread _thread = new System.Threading.Thread(() => bki.BKICalculation(_carId, _userId));
        _thread.Start();

        System.Diagnostics.Stopwatch _stopwatch = new System.Diagnostics.Stopwatch();
        _stopwatch.Start();

        bool _threadRunning = true;
        while (_threadRunning)
        {
            if (_thread.IsAlive)
            {
                if (_stopwatch.Elapsed.Seconds > 30)
                {
                    _thread.Abort();
                    _threadRunning = false;
                }
            }
            else
                _threadRunning = false;
        }
        _stopwatch.Stop();
    }

    private string getProviderLogoCss(string _companyId, string _type)
    {
        string _class = string.Empty;
        if (_type == "result")
        {
            if (_companyId == "11")
            {
                _class = "allianz-cp";
            }
            else if (_companyId == "12")
            {
                _class = "msig";
            }
            else if (_companyId == "16")
            {
                _class = "axa";
            }
            else if (_companyId == "29")
            {
                _class = "lmg";
            }
            else if (_companyId == "31")
            {
                _class = "aig";
            }
            else if (_companyId == "32")
            {
                _class = "bki";
            }
            else if (_companyId == "33")
            {
                _class = "muangthai";

            }
            else if (_companyId == "35")
            {
                _class = "krungthai";

            }
            else if (_companyId == "39")
            {
                _class = "mittare";

            }
            else if (_companyId == "41")
            {
                _class = "ksk";
            }
            else if (_companyId == "43")
            {
                _class = "synmunkong";

            }
            else if (_companyId == "45")
            {
                _class = "viriyah";

            }
            else if (_companyId == "46")
            {
                _class = "tokiomarine";
            }
            else if (_companyId == "51")
            {
                _class = "scsmg";

            }
            else if (_companyId == "58")
            {
                _class = "thaivivat";

            }
            else if (_companyId == "65")
            {
                _class = "dhipaya";

            }
            else if (_companyId == "66")
            {
                _class = "thaipaiboon";

            }
            else if (_companyId == "67")
            {
                _class = "deves";

            }
            else if (_companyId == "68")
            {
                _class = "thaisri";

            }
            else if (_companyId == "69")
            {
                _class = "asset";

            }
        }
        return _class;
    }

    private string GetInsuranceTypeName(Int32 InsType)
    {
        string _strInsType = "";
        if (InsType == 10 || InsType == 11)
        {
            _strInsType = Resources.CarInsurance.Insurance_ClassOne;
        }
        if (InsType == 21)
        {
            _strInsType = Resources.CarInsurance.Insurance_ClassTwoPlus;
        }
        if (InsType == 31)
        {
            _strInsType = Resources.CarInsurance.Insurance_ClassThreePlus;
        }
        if (InsType == 30)
        {
            _strInsType = Resources.CarInsurance.Insurance_ClassThree;
        }
        return _strInsType;
    }

    public Int32 CheckCallMeCount()
    {
        try
        {
            string CarId = "0";
            string UserId = "0";
            if (Session[CE.Global.General.CarId] != null)
            {
                CarId = Session[CE.Global.General.CarId].ToString();
            }
            if (Session[CE.Global.General.UserId] != null)
            {
                UserId = Session[CE.Global.General.UserId].ToString();
            }
            DataTable _dt = new DataTable();
            MyDatabase _db = new MyDatabase();
            string _sqlString = @"SELECT COUNT(*) RECORDCOUNT FROM tblContactUser WHERE ProductId = " + CarId + " AND RefCEUserId = " + UserId;
            _sqlString += " AND (CONVERT(VARCHAR(8),ModifiedDate,112) BETWEEN CONVERT(VARCHAR(8),DATEADD(DD, -60,dbo.fn_getUTCDateTime()),112) ";
            _sqlString += " AND CONVERT(VARCHAR(8),dbo.fn_getUTCDateTime(),112))";
            _dt = _db.GetDataTable(_sqlString);
            _db = null;

            string rtnCount = "0";
            Int32 _retResult = 0;
            if (_dt != null && _dt.Rows[0]["RECORDCOUNT"] != null)
            {
                rtnCount = _dt.Rows[0]["RECORDCOUNT"].ToString();
            }
            if (rtnCount != null)
            {
                if (!Int32.TryParse(rtnCount.ToString(), out _retResult))
                {
                    _retResult = 0;
                }
            }
            return _retResult;
        }
        catch (Exception ex)
        {
            return -1;
        }
    }

    #region Call Me - No match found

    private void LoadTitles()
    {
        lblApplicationTitle.Text = Resources.CarMenu.NoMatchFound;
        //lblNomatch.Text = Resources.CarMenu.TakeNote;
        lblCallUsBack.Text = Resources.CarMenu.CallYouBack;
        lblCallUs.Text = Resources.CarMenu.OR + " " + Resources.CarMenu.Callus + " ";
        lblThanksTitle.Text = Resources.CarMenu.ThankYou;
        lblMessage1.Text = Resources.CarMenu.CallMeMessage;
        lblMessage2.Text = Resources.CarMenu.HotLineMessage;
        btnSubmit.Text = Resources.ProposalForm.Submit;
    }

    private string EmailAddress
    {
        get { return txtEmail.Text.Trim(); }
    }

    private string MobileNumber
    {
        get { return txtMobile.Text.Trim(); }
    }

    private string Name
    {
        get { return txtName.Text.Trim(); }
    }

    private void SetCookies()
    {
        try
        {
            string _isAccept = "FALSE";
            if (hdnIsAceept.Value == "TRUE")
            {
                _isAccept = "TRUE";
            }
            HttpCookie _cookie = new HttpCookie("GGMobileQuote");
            _cookie.Values.Add("CustomerName", MySecurity.Encrypt(txtName.Text, true));
            _cookie.Values.Add("CustomerEmail", MySecurity.Encrypt(txtEmail.Text, true));
            _cookie.Values.Add("CustomerMobile", MySecurity.Encrypt(txtMobile.Text, true));
            _cookie.Values.Add("IsAccept", MySecurity.Encrypt(_isAccept, true));
            _cookie.Expires = DateTime.Now.AddDays(90);
            Response.Cookies.Add(_cookie);
        }
        catch (Exception Ex)
        {
            Ex = null;
        }
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        txtName.Text = HttpUtility.HtmlEncode(txtName.Text.Trim());
        txtEmail.Text = HttpUtility.HtmlEncode(txtEmail.Text);
        txtMobile.Text = HttpUtility.HtmlEncode(txtMobile.Text);

        #region CallMeTime
        //CallMeTime
        if (rfvCallMeTime.Enabled && rfvCallMeTime.ValidationGroup == strValidationGroup)
        {
            rfvCallMeTime.Validate();
            if (rfvCallMeTime.IsValid == false)
            {
                ddlCallMeTime.ControlStyle.CssClass = "dropdown-fields validationError";
            }
            else
            {
                ddlCallMeTime.ControlStyle.CssClass = "dropdown-fields";
            }
        }
        else
        {
            ddlCallMeTime.ControlStyle.CssClass = "dropdown-fields";
        }
        #endregion

        #region User
        //Name
        if (rfvName.Enabled && rfvName.ValidationGroup == strValidationGroup)
        {
            rfvName.Validate();
            if (rfvName.IsValid == false)
            {
                txtName.ControlStyle.CssClass = "text-fields validationError";
            }
            else
            {
                txtName.ControlStyle.CssClass = "text-fields";
            }
        }
        else
        {
            txtName.ControlStyle.CssClass = "text-fields";
        }

        if (revName.Enabled && revName.ValidationGroup == strValidationGroup)
        {
            if (rfvName.IsValid)
            {
                revName.Validate();
                if (revName.IsValid == false)
                {
                    txtName.ControlStyle.CssClass = "text-fields validationError";
                }
                else
                {
                    txtName.ControlStyle.CssClass = "text-fields";
                }
            }
        }
        else
        {
            txtName.ControlStyle.CssClass = "text-fields";
        }

        //Email
        if (rfvEmail.Enabled && rfvEmail.ValidationGroup == strValidationGroup)
        {
            rfvEmail.Validate();
            if (rfvEmail.IsValid == false)
            {
                txtEmail.ControlStyle.CssClass = "text-fields validationError";
            }
            else
            {
                txtEmail.ControlStyle.CssClass = "text-fields";
            }
        }
        else
        {
            txtEmail.ControlStyle.CssClass = "text-fields";
        }

        if (revEmail.Enabled && revEmail.ValidationGroup == strValidationGroup)
        {
            if (rfvEmail.IsValid)
            {
                revEmail.Validate();
                if (revEmail.IsValid == false)
                {
                    txtEmail.ControlStyle.CssClass = "text-fields validationError";
                }
                else
                {
                    txtEmail.ControlStyle.CssClass = "text-fields";
                }
            }
        }
        else
        {
            txtEmail.ControlStyle.CssClass = "text-fields";
        }

        //Mobile No
        if (rfvMobile.Enabled && rfvMobile.ValidationGroup == strValidationGroup)
        {
            rfvMobile.Validate();
            if (rfvMobile.IsValid == false)
            {
                txtMobile.ControlStyle.CssClass = "text-fields validationError";
            }
            else
            {
                txtMobile.ControlStyle.CssClass = "text-fields";
            }
        }
        else
        {
            txtMobile.ControlStyle.CssClass = "text-fields";
        }

        if (revMobile.Enabled && revMobile.ValidationGroup == strValidationGroup)
        {
            if (rfvMobile.IsValid)
            {
                revMobile.Validate();
                if (revMobile.IsValid == false)
                {
                    txtMobile.ControlStyle.CssClass = "text-fields validationError";
                }
                else
                {
                    txtMobile.ControlStyle.CssClass = "text-fields";
                }
            }
        }
        else
        {
            txtMobile.ControlStyle.CssClass = "text-fields";
        }
        #endregion
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            ChangeValidationEffectServerSide("callme");
            Page.Validate("callme");
            if (Page.IsValid)
            {
                if (txtMobile.Text.Trim().Length == 10)
                {
                    Int64 _userId = 0;
                    Int64 _carId = 0;
                    Int64 _ProviderId = 0;
                    Int64 _ExistingUserId = 0;
                    string ExistingEmail = "";
                    if (Session[General.UserEmail] != null && Session[General.UserEmail].ToString() != string.Empty)
                    {
                        ExistingEmail = Session[General.UserEmail].ToString();
                    }
                    if (Session[CE.Global.General.UserId] != null)
                    {
                        if (!Int64.TryParse(Session[General.UserId].ToString(), out _ExistingUserId))
                        {
                            _ExistingUserId = 0;
                        }
                    }
                    if (Session[General.CarId] != null)
                    {
                        if (!Int64.TryParse(Session[General.CarId].ToString(), out _carId))
                        {
                            _carId = 0;
                        }
                    }

                    #region Customer Details
                    Account _useraccount = new Account();
                    AccountDB _useraccountdb = new AccountDB();

                    _useraccount = _useraccountdb.GetUserAccount(EmailAddress, 400);
                    if (_useraccount != null && _useraccount.CEID > 0)
                    {
                        _userId = _useraccount.CEID;
                        Profile _userprofile = new Profile();
                        ProfileDB _userprofiledb = new ProfileDB();

                        Contact _usercontact = new Contact();
                        ContactDB _usercontactdb = new ContactDB();

                        Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                        _userprofile = _userprofiledb.GetProfile(_useraccount.CEID);

                        if (_userprofile != null && _userprofile.ProfileId > 0)
                        {
                            _userprofile.SurName = string.Empty;
                            _userprofile.FirstName = Server.HtmlEncode(txtName.Text);
                            _userprofile.IsAcceptTC = true;
                            _userprofiledb.Insert(_userprofile);
                        }
                        _usercontact = _usercontactdb.GetContact(_useraccount.CEID);
                        if (_usercontact != null && _usercontact.ContactId > 0)
                        {
                            _usercontact.Mobile = txtMobile.Text.Trim();
                            _usercontactdb.Insert(_usercontact);
                        }
                        Session[CE.Global.General.UserId] = _useraccount.CEID;
                        Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                        Session[CE.Global.General.UserEmail] = _useraccount.Email;
                        Session[CE.Global.General.UserName] = _userprofile.FirstName;
                        Session[CE.Global.General.IsAcceptTC] = "0";
                        if (_userprofile.IsAcceptTC == true)
                        {
                            Session[CE.Global.General.IsAcceptTC] = "1";
                        }
                        Session[CE.Global.General.UserPhoneNo] = _usercontact.Mobile;
                        _useraccount = null;
                        _useraccountdb = null;
                        _userprofile = null;
                        _userprofiledb = null;
                        _usercontact = null;
                        _usercontactdb = null;
                        if (_ExistingUserId != _userId)
                        {
                            UpdateUserIdCarDetails(_carId, _userId, _ExistingUserId, ExistingEmail, "SWITCH", txtEmail.Text.Trim().ToLower(), Session[General.UserName].ToString(), txtMobile.Text.Trim());
                        }
                    }
                    else
                    {
                        //General.ClearAllSession(this.Page, "USER");
                        UpdateProfile(_userId, _carId);
                        if (Session[CE.Global.General.UserId] != null)
                        {
                            if (!Int64.TryParse(Session[CE.Global.General.UserId].ToString(), out _userId))
                            {
                                _userId = 0;
                            }
                        }
                        UpdateUserIdCarDetails(_carId, _userId, _ExistingUserId, ExistingEmail, "SWITCH", txtEmail.Text.Trim().ToLower(), Session[General.UserName].ToString(), txtMobile.Text.Trim());
                        SendMailToUser(Session[CE.Global.General.UserEmail].ToString(), Session[CE.Global.General.UserName].ToString(), Session[CE.Global.General.UserPhoneNo].ToString());
                        //if (UpdateProfile(_userId, 0) > 0)
                        //{
                        //    //SendMailToUser(EmailAddress, Name, MobileNumber);

                        //    Session["CLASSTYPE"] = "1";
                        //    _userId = Convert.ToInt64(Session[General.UserId].ToString());
                        //}
                    }
                    SetCookies();
                    #endregion

                    if (Session[General.UserId] != null)
                    {
                        if (!Int64.TryParse(Session[General.UserId].ToString(), out _userId))
                        {
                            _userId = 0;
                        }
                        if (!Int64.TryParse(Session[General.CarId].ToString(), out _carId))
                        {
                            _carId = 0;
                        }
                    }

                    if (IsValid)
                    {
                        #region Call Me
                        string _message = "";
                        string _title = "";

                        _message = "Customer Name: " + Server.HtmlEncode(txtName.Text);
                        _title = "<mobile> Result not found - Call me now - Request by " + Server.HtmlEncode(txtName.Text);

                        Int64 _result = 0;
                        ContactUser _cu = new ContactUser();
                        ContactUserDB _cudb = new ContactUserDB();
                        string strInsType = "";
                        if (Request.Params["instype"] != null && Request.Params["instype"].ToString() != string.Empty)
                        {
                            strInsType = Request.Params["instype"].ToString();
                        }
                        if (strInsType == "10")
                        {
                            strInsType = "1";
                        }
                        else if (strInsType == "11")
                        {
                            strInsType = "1+";
                        }
                        else if (strInsType == "21")
                        {
                            strInsType = "2+";
                        }
                        else if (strInsType == "30")
                        {
                            strInsType = "3+";
                        }
                        else if (strInsType == "31")
                        {
                            strInsType = "3+";
                        }

                        _cu.InsuranceType = "CI-" + strInsType;
                        _cu.ProductId = _carId;
                        _cu.RefCEUserId = _userId;
                        _cu.ProviderCompanyId = _ProviderId;
                        _cu.ContactNo = Server.HtmlEncode(txtMobile.Text);
                        _cu.FullName = Server.HtmlEncode(txtName.Text);
                        _cu.CallTime = Convert.ToInt16(ddlCallMeTime.Text);

                        if (Request.Params["spc"] != null)
                        {
                            if (Request.Params["spc"].ToString() == "1")
                            {
                                _cu.Info1 = "GG Promotion";
                            }
                        }
                        _cu.Info2 = "RESULTNOTFOUND";
                        _cu.Info3 = "MOBILE";

                        _result = _cudb.Insert(_cu);

                        if (_result > 0)
                        {
                            #region Hide Call me email sending - Sakthi on 11 Dec 2014
                            //_message += "<br/><br/>Email : " + txtEmail.Text;
                            //_message += "<br/><br/>Contact No : " + txtMobile.Text.Trim();
                            //_message += "<br/><br/>Call Time : " + ddlCallMeTime.SelectedItem.Text;
                            //string _emailList = ConfigurationManager.AppSettings["Mobile.TH.CICallMeReceiver"].ToString();
                            //MyMailManager.SendNotification(_emailList, _title, _message);
                            #endregion
                        }

                        #endregion
                        CE.Global.General.ClearAllSession(this.Page, "CI");
                        Response.Redirect("car-not-found.aspx?sent=1");
                    }
                }
            }
        }
        catch (Exception ex)
        {
        }
    }

    private Int64 UpdateProfile(Int64 UserId, Int64 CarId)
    {
        Int64 _retValue = 0;

        if (UserId != 0)
        {
            Profile _profile = new Profile();
            ProfileDB _profiledb = new ProfileDB();

            Contact _contact = new Contact();
            ContactDB _contactdb = new ContactDB();

            _profile = _profiledb.GetProfile(UserId);
            _contact = _contactdb.GetContact(UserId);
            _retValue = UserId;
            if (_profile != null)
            {
                #region Update Profile

                _profile.Salutation = "";
                _profile.FirstName = HttpUtility.HtmlEncode(txtName.Text);
                _profile.SurName = "";
                if (_profile.DOB.Year == 1900)
                {
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _profile.DOB = dteDOB;
                }
                if (_profile.Gender.ToString().Trim() == "")
                {
                    _profile.Gender = 'M';
                }
                _profile.Status = "Complete";
                _profile.IsAcceptTC = true;

                _retValue = _profiledb.Insert(_profile);

                if (_retValue > 0 && _contact != null)
                {
                    _contact.Mobile = txtMobile.Text.Trim();
                    _contact.Status = true;

                    _retValue = _contactdb.Insert(_contact);
                }

                if (_retValue > 0)
                {
                    if (_profile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = _profile.FirstName + " " + _profile.SurName;
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = _profile.SurName;
                    }
                    Session[CE.Global.General.IsAcceptTC] = "0";
                    if (_profile.IsAcceptTC == true)
                    {
                        Session[CE.Global.General.IsAcceptTC] = "1";
                    }
                    if (_contact != null)
                    {
                        Session[General.UserPhoneNo] = _contact.Mobile;
                    }
                    Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                }

                _profile = null;
                _contact = null;
                #endregion
            }
        }
        else
        {
            _retValue = SaveNewCustomer();
            UserId = _retValue;
        }
        return _retValue;
    }

    private Int64 SaveNewCustomer()
    {
        #region New Customer
        Int64 _retVal = 0;
        if (Page.IsValid)
        {

            Account _useraccount = new Account();
            AccountDB _useraccountdb = new AccountDB();

            Profile _userprofile = new Profile();
            ProfileDB _userprofiledb = new ProfileDB();

            Contact _contact = new Contact();
            ContactDB _contactdb = new ContactDB();

            _useraccount = _useraccountdb.GetUserAccount(txtEmail.Text.Trim(), 400);
            if (_useraccount != null)
            {
                if (_useraccount.CEID > 0)
                {
                    _retVal = _useraccount.CEID;
                    _contact = _contactdb.GetContact(_useraccount.CEID);
                    Session[CE.Global.General.UserId] = _useraccount.CEID;
                    Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                    Session[CE.Global.General.UserEmail] = _useraccount.Email;
                    Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                    Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                    _userprofile = _userprofiledb.GetProfile(_useraccount.CEID);
                    if (_userprofile != null && _userprofile.ProfileId > 0)
                    {
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                    }
                }
            }
            else
            {

                long _result = -1;
                _useraccount = new Account();
                _useraccount.Email = txtEmail.Text.Trim().ToLower();
                string _authcode = txtMobile.Text.Trim();
                _useraccount.AuthCode = _authcode;
                _useraccount.UserId = "CEUSERAUTOIDMOBILECI";
                _useraccount.UserTypeId = 400;
                _useraccount.IsAcceptTC = false;
                _useraccount.Status = true;
                _useraccount.RefCEUserID = -1;
                _result = _useraccountdb.Insert(_useraccount);
                _useraccount.CEID = _result;
                _retVal = _useraccount.CEID;
                if (_result > 0)
                {
                    _userprofile.Salutation = "";
                    _userprofile.FirstName = Server.HtmlEncode(txtName.Text);
                    _userprofile.SurName = "";
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _userprofile.DOB = dteDOB;
                    _userprofile.Gender = 'M';

                    _userprofile.Occupation = 140;
                    _userprofile.Status = "Complete";
                    _userprofile.RefCEUserId = _useraccount.CEID;
                    _userprofile.IsAcceptTC = true;
                    _result = _userprofiledb.Insert(_userprofile);

                    _contact.Email = _useraccount.Email;
                    _contact.Mobile = txtMobile.Text.Trim();

                    _contact.Status = true;
                    _contact.RefCEUserId = _useraccount.CEID;
                    _result = _contactdb.Insert(_contact);

                    if (_result > 0)
                    {
                        Session[CE.Global.General.UserId] = _useraccount.CEID;
                        Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                        Session[CE.Global.General.UserEmail] = _useraccount.Email;
                        Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                        Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                        Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                        Session[CE.Global.General.IsAcceptTC] = "0";
                        if (_userprofile.IsAcceptTC == true)
                        {
                            Session[CE.Global.General.IsAcceptTC] = "1";
                        }
                    }

                }

            }
        }
        else
        {
            _retVal = 0;
        }

        return _retVal;
        #endregion
    }

    private void UpdateUserIdCarDetails(Int64 CarId, Int64 UserId, Int64 ExistingUserId, string ExistingEmail, string ChangeStatus, string Email, string Name, string Mobile)
    {
        try
        {
            Int64 _result = -1;
            MyDatabase _db = new MyDatabase();
            DataTable _dtResult = new DataTable();
            string _spName = "sprocCarDetailUpdateSingleItemByUserId";
            SortedList _sPara = new SortedList();
            _sPara.Add("@CarId", CarId);
            _sPara.Add("@RefCEUserId", UserId);
            _sPara.Add("@ExistingUserId", ExistingUserId);
            _sPara.Add("@ExistingEmail", ExistingEmail);
            _sPara.Add("@ChangeStatus", ChangeStatus);
            _sPara.Add("@Email", Email);
            _sPara.Add("@Name", Name);
            _sPara.Add("@Mobile", Mobile);

            _result = _db.ExecuteNonSqlSP(_spName, _sPara);
        }
        catch (Exception ex)
        {
        }
    }

    private bool SendMailToUser(string EmailAddress, string UserName, string AuthCode)
    {
        bool _retVal = false;
        _retVal = CE.Email.Welcome.SendMail(EmailAddress, UserName, AuthCode);
        return _retVal;
    }

    #endregion     

}
